课程名称: Python办公自动化
课程章节:第4章 xlsxwriter生成图表
课程讲师: 离岛
课程内容:
xlsxwriter作为Python第三方模块,用于向生成的Excel表格插入数据、图表等操作
安装:pip install xlsxwriter
导入:import xlsxwriter
通过启动内存优化模式来加快数据的写入
不足的地方是不支持读取xlsx文件,这个可以通过前面的方式来读取
import xlsxwriter
wb = xlsxwriter.Workbook("data.xlsx")
# 创建sheet
sheet = wb.add_worksheet("newsheet")
#写入
# sheet.write_string()
# 根据输入的数据类型进行映射,比如输入数字 调用write_number, 字符串则是write_string
sheet.write(0, 0, "2022年度")
sheet.merge_range(1, 0, 2, 2, "第一季度销售统计")
data = (
["一月份", 500, 450],
["二月份", 600, 450],
["三月份", 700, 550]
)
sheet.write_row(3, 0, ["月份", "预期销售额", "实际的销售额"])
# 写入数据
for index, item in enumerate(data):
sheet.write_row(index + 4, 0, item)
#写excle公式
sheet.write(7, 1, "=SUM(B5:B7)")
sheet.write(7, 2, '=SUM(C5:C7)')
sheet.write_url(9, 0, "http://www.baidu.com", string="更多数据")
sheet.insert_image(10, 0, "view.png") # 插入图片#
wb.close()以上截图为write_XXX方法,包含了需要写入的各种类型
#格式化对象,一种是通过字典的方式
cell_format = wb.add_format({'blod':True, })
#另一种方式是通过接口直接设置
cell_format1.set_bold() # 设置加粗
cell_format1.set_font_color("red") # 文本的颜色
cell_format1.set_font_size(14)
cell_format1.set_align("center") # 对齐方式
cell_format2 = wb.add_format() # 格式对象
cell_format2.set_bg_color("#808080") # 设置背景颜色cell_format1 = wb.add_format() # 格式对象
sheet.merge_range(1, 0, 2, 2, "第一季度销售统计", cell_format)接口说明可以参考官方指导说明文档
https://xlsxwriter.readthedocs.io
https://xlsxwriter.readthedocs.io/format.html
仍然有些接口和具体参数的确定需要话也可以参考如下文章内的说明
https://blog.csdn.net/shammy_feng/article/details/124149896
课程收获:
本次课程学习到xlsxwrite这个第三方提供的写入表格数据的另一种选择并且优于xlwt模块,从最开始的创建到最后的表格格式化修改都学习到很多。