这篇文章主要介绍了关于python XlsxWriter模块创建aexcel表格,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
安装使用pip install XlsxWriter来安装,Xlsxwriter用来创建excel表格,功能很强大,下面具体介绍:
1.简单使用excel的实例:
#coding:utf-8 import xlsxwriter workbook = xlsxwriter.Workbook('d:\\suq\\test\\demo1.xlsx') #创建一个excel文件 worksheet = workbook.add_worksheet('TEST') #在文件中创建一个名为TEST的sheet,不加名字默认为sheet1 worksheet.set_column('A:A',20) #设置第一列宽度为20像素 bold = workbook.add_format({'bold':True}) #设置一个加粗的格式对象 worksheet.write('A1','HELLO') #在A1单元格写上HELLO worksheet.write('A2','WORLD',bold) #在A2上写上WORLD,并且设置为加粗 worksheet.write('B2',U'中文测试',bold) #在B2上写上中文加粗 worksheet.write(2,0,32) #使用行列的方式写上数字32,35,5 worksheet.write(3,0,35.5) #使用行列的时候第一行起始为0,所以2,0代表着第三行的第一列,等价于A4 worksheet.write(4,0,'=SUM(A3:A4)') #写上excel公式 worksheet.insert_image('B5','f:\\1.jpg') #插入一张图片 workbook.close()
2.常用方法说明
1.Workbook类
Workbook类创建一个XlsxWriter的Workbook对象,代表整个电子表格文件,存储到磁盘上.
add_worksheet():用来创建工作表,默认为sheet1
add_format():创建一个新的格式对象来格式化单元格,例如bold=workbook.add_format({'bold':True})
还可以使用set_bold,例如:bold=workbook.add_format() bold.set_bold()
#border:边框,align:对齐方式,bg_color:背景颜色,font_size:字体大小,bold:字体加粗 top = workbook.add_format({'border':1,'align':'center','bg_color':'cccccc','font_size':13,'bold':True})
add_chart(options):创建一个图表对象,内部是使用insert_chart()方法来实现的,options(dict类型)为图表指定一个字典属性
close():关闭文件
2.Worksheet类
worksheet代表一个Excel的工作表,是XlsxWriter的核心,下面是几个核心方法
write(row,col,*args):写普通数据到工作表的单元格,row行坐标,col列坐标,起始都是以0开始,*args为写入的内容,可以是字符串,文字,公式等,writer方法已经作为其它更具体数据类型方法的别名
write_string():写入字符串类型,worksheet.write_string(0,0,'your text')
write_number():写入数字类型,worksheet.write_number('A2',1.1)
write_blank():写入空类型数据,worksheet.write_blank('A2',None)
wirte_formula():写入公式类型,worksheet.write_formula(2,0,'=SUM(B1:B5))
write_datetime():写入日期类型数据,worksheet.write_datetime(7,0,datetime.datetime.strptime('2014-01-02','%Y-%m-%d),workbook.add_format({'num_format':'yyyy-mm-dd'}));
write_boolean():写入逻辑类数据,worksheet.write_boolean(0,0,True)
write_url():写入超链接类型数据,worksheet.write_url('A1','ftp://www.python.org')
write_column():写入到一列,后面接一个数组
wirte_row():写入到一行,后面接一个数组
set_row(row,height,cell_format,options):此方法设置行单元格的属性,row指定行位置,height指定高度,单位是像素,cell_format
指定格式对象,参数options设置hiddeen(隐藏),level(组合分级),collapsed(折叠,例如:
cell_format=workbook.add_format({'bold':True})
worksheet.set_row(0,40,cell_format) 设置第一行高40,加粗
set_column(first_col,last_col,width,cell_format,options):
设置列单元格的属性,具体参数说明如上.worksheet.set_column(0,1,10) worksheet.set_column('C:D',20)
insert_image(row,col,image[,options]):此方法是插入图片到指定单元格
例如插入一个图片的超链接为www.python.org
worksheet.insert_image('B5','f:\\1.jpg',{'url':'http://www.python.org'})
3.Chart类
Chart类实现XlsxWriter模块中的图标组件的基类,支持的图表类型包括面积,条形图,柱形图,折形图,饼图,散点图,股票和雷达. 一个图表对象是通过Workbook的add_chart方法创建,通过{type,'图表类型'}字典参数指定图表的类型,语句如下:
chart = workbook.add_chart({type,'column'}) #创建一个column图表
更多图表类型说明:
area:创建一个面积样式的图表;
bar:创建一个条形样式的图表;
column:创建一个柱形样式的图表;
line:创建一个线条样式的图表
pie:创建一个饼图样式的图表
scatter:创建一个散点样式的图表
stock:创建一个股票样式的图表;
radar:创建一个雷达央视的图表
然后通过insert_chart()方法插入到指定的位置,语句如下:
worksheet.insert_chart('A7',chart)
chart.add_series(options)方法,作用是添加一个数据系列到图表,参数options(dict类型)设置图表系列选项的字典,操作示例如下:
chart.add_series({ 'categories':'=Sheet1!$A$$1:$A$5', 'values':'=Sheet1!$A$$1:$A$5', 'line':={'color':'red'} })
categories,values,line最为常用,categories作用是设置图表类别标签范围;values是设置图表数据范围,line为设置图表线条属性,包括颜色宽度等.
set_x_axis(options):设置图表X轴选项,例如:
chart.set_x_axis({ 'name':'EARNING per quarter', 'name_font':{'size':14,'bold':True}, 'num_font':{'italic':True} })
set_size(options):设置图表的大小,如
chart.set_size({'width':720,'height':576})
set_title(options):设置标题,如chart.set_title({'name':'TEST TITLE'}
set_style(style_id):设置图表样式,
set_table(options):设置x轴为数据表格式
下面是一个创建文件系统使用率的实例:
#coding:utf-8 import xlsxwriter workbook = xlsxwriter.Workbook('d:\\suq\\test\\demo1.xlsx') #创建一个excel文件 worksheet = workbook.add_worksheet('sheet1') #在文件中创建一个sheet #border:边框,align:对齐方式,bg_color:背景颜色,font_size:字体大小,bold:字体加粗 top=workbook.add_format({'border':6,'align':'center','bg_color':'cccccc','font_size':13,'bold':True}) #设置单元格格式 title=[u'文件系统',u'总容量',u'使用大小',u'剩余大小'] #设置第一行标题信息 buname=['/dev/mapper/vg_basic-lv_root','tmpfs','/dev/sda1'] #设置左边第一排信息 worksheet.write_row('A1',title,top) worksheet.write_column('A2',buname,top) worksheet.set_column('A:D',40) #A到D列设置宽度,宽度设置必须是整列设置,高度必须是整行设置 #worksheet.set_row(0,40) #设置第一行高度为40像素 format_data=workbook.add_format({'align':'center','font_size':13}) #设置单元格格式 data=[[17678,4393,12388],[9768,8900,868],[24285,2715,21000]] #模拟文件系统的数据,data[0],[1],[2]分别表示全部空间,使用空间,剩余空间 worksheet.write_row('B2',data[0],format_data) #将数据写入,这里安装整行写入 worksheet.write_row('B3',data[1],format_data) worksheet.write_row('B4',data[2],format_data) chart=workbook.add_chart({'type':'column'}) #创建表格,表格类型为column chart.set_title({'name':u'文件系统使用率'}) #设置表格的title for i in ['B','C','D']: chart.add_series({ 'categories': 'sheet1!$A$2:$A$4', 'values':'sheet1!$'+i+'$2:$'+i+'$4', 'name':'=sheet1!$'+i+'$1' }) #注意上面的表格中,每一行的数据在图中会显示在一起,也就是说values为B2:B4 chart.set_size({'width':800,'height':500}) #设置表格的大小 chart.set_y_axis({'name': 'MB'}) #设置表格y轴信息 #chart.set_style(33) #设置表格的样式 worksheet.insert_chart('A8',chart) #插入表格 workbook.close()
显示的图片结果如下:
相关推荐:
使用python实现XlsxWriter创建Excel文件并编辑
The above is the detailed content of python XlsxWriter module creates aexcel table. For more information, please follow other related articles on the PHP Chinese website!

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.