xlsxwriter模块

一、xlsxwriter模块

用于向生成的excel表格插入数据、表格等,相较xlwt支持更多excel功能,100%兼容excel xlsx文件,支持excel2003,excel2007等版本,处理速度更快,支持大文件写入,不支持读取和修改excel文件。

安装:pip install xlsxwriter

导入:import xlsxwriter

Ctrl+Alt+L   进行格式化

# -*- coding:utf-8 -*-
import xlsxwriter
#创建工作簿
xl=xlsxwriter.Workbook("data.xlsx")
#格式对象 加粗
cell_format=xl.add_format({'bold':True})
cell_format1=xl.add_format()
cell_format1.set_bold() #加粗
cell_format1.set_font_color("red")#字体颜色
cell_format1.set_font_size(14) #字体大小
cell_format1.set_align("center")#居中
cell_format2=xl.add_format()
cell_format2.set_bg_color("#808080")#背景颜色
#创建工作表
ws=xl.add_worksheet("newsheet")
ws.write(0,0,"2020年",cell_format)
#合并单元格2-3行,1-3列
ws.merge_range(1,0,2,2,"第一季度销售额",cell_format1)  #行起始,列起始,行终止,列终止
#Ctrl+Alt+L   进行格式化
data=(["一月", 500, 450],
      ["二月", 600, 500],
      ["三月", 700, 500]
      )
ws.write_row(3,0,["月份","预计","实际"],cell_format2)
#for循环写入数据
for i,item in enumerate(data):
        ws.write_row(i+4,0,item)
#写入excel公式
ws.write(7,1,"=sum(B5:B7)")
ws.write(7,2,"=sum(C5:C7)")
#写入超链接
ws.write_url(9,0,"http://www.baidu.com",string="更多数据")
#插入图片
ws.insert_image(10,0,"11.bmp")

#写入图表 柱状图column(折线图:line)
chart=xl.add_chart({'type':'column'})
chart.set_title({'name':'第一季度销售额'})
#X Y轴信息
chart.set_x_axis({'name':'月份'})
chart.set_y_axis({'name':'销售额'})
#数据
chart.add_series({
    'name':'预期销售额',
    'categories':'=newsheet!$A$5:$A$7',
    'values':['newsheet',4,1,6,1]
}
)
chart.add_series({
    'name':'实际销售额',
    'categories':'=newsheet!$A$5:$A$7',
    'values':['newsheet',4,2,6,2],
    'data_labes':{'value':True}
}
)
ws.insert_chart('H23',chart)
#关闭工作簿
xl.close()

结果:

 

posted @ 2021-01-21 20:34  bellin124  阅读(236)  评论(0编辑  收藏  举报