Xlsx是python用来构造xlsx文件的模块,可以向excel2007+中写text,numbers,formulas 公式以及hyperlinks超链接。
可以完成xlsx文件的自动化构造,包括:
合并单元格,制作excel图表等功能:
1,Introduction:
xlsxWriter支持多种excle功能;与excel完美兼容;写大文件,速度快且只占用很小的内存空间
不支持读或者改现有的excel文件
2, Installing:
sudo pip install XlsxWriter;
sudo easy_install XlsxWriter;
或者源码安装:http://github.com/jmcnamara/XlsxWriter/archive/master.tar.gz
3,使用:
import xlsxwriter workbook = xlsxwriter.Workbook(‘hello.xlsx‘) # 建立文件 worksheet = workbook.add_worksheet() # 建立sheet, 可以work.add_worksheet(‘employee‘)来指定sheet名,但中文名会报UnicodeDecodeErro的错误 worksheet.write(‘A1‘, ‘Hello world‘) # 向A1写入 workbook.close()
excel公式计算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
excel自定义格式:
import xlsxwriter # 建文件及sheet. workbook = xlsxwriter.Workbook(‘Expenses02.xlsx‘) worksheet = workbook.add_worksheet() # Add a bold format to use to highlight cells. 设置粗体,默认是False bold = workbook.add_format({‘bold‘: True}) # Add a number format for cells with money. 定义数字格式 money = workbook.add_format({‘num_format‘: ‘$#,##0‘}) # Write some data headers. 带自定义粗体blod格式写表头 worksheet.write(‘A1‘, ‘Item‘, bold) worksheet.write(‘B1‘, ‘Cost‘, bold) # Some data we want to write to the worksheet. expenses = ( [‘Rent‘, 1000], [‘Gas‘, 100], [‘Food‘, 300], [‘Gym‘, 50], ) # Start from the first cell below the headers. row = 1 col = 0 # Iterate over the data and write it out row by row. for item, cost in (expenses): worksheet.write(row, col, item) # 带默认格式写入 worksheet.write(row, col + 1, cost, money) # 带自定义money格式写入 row += 1 # Write a total using a formula. worksheet.write(row, 0, ‘Total‘, bold) worksheet.write(row, 1, ‘=SUM(B2:B5)‘, money) workbook.close()
excel写入时间格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
|
@@@ write方法提供了python类型到excel类型的转换, XlsxWriter支持excel工作表最大1048576行记录,16384条列记录,超出可以选择再建新sheet
1 2 3 4 5 6 7 |
|
关于更多字符串、数字、颜色及位置等excel格式:http://xlsxwriter.readthedocs.io/format.html
4, 图标
这个是我比较关注的利用excel工具进行图标统计的功能
相比较python的matplotlib的画图模块,excel的图标更加漂亮灵活一些
Chart: Area, Bar, Column, Doughnut, Line, Pie, Scatter, Stock, Radar
workbook = xlswriter.Workbook(‘chart.xls‘)
worksheet = workbook.add_sheet(‘First_example‘) # 普通工作表
建立Chart对象: chart = workbook.add_chart({type, ‘column‘})
将图插入到sheet中: worksheet.insert_chart(‘A7‘, chart)
或者可以建立图表工作表chartsheet
chartsheet = workbook.add_charsheet()
chartsheet.set_char(chart)
柱状图:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
workbook.add_chart({‘type‘:‘column‘}) # 默认格式
workbook.add_chart({‘type‘:‘column‘, ‘substyle‘:‘percent_stacked‘}) # 按百分比展示
workbook.add_chart({‘type‘:‘column‘, ‘substyle‘:‘stacked‘})
其他类型chart也是这样: