xlsxwriter格式化配置

官方文档:

https://xlsxwriter.readthedocs.io/format.html

格式化配置

#格式化配置
import xlsxwriter #导入模块

#创建工作簿对象
wb = xlsxwriter.Workbook("data.xlsx")

#创建格式对象
cell_format = wb.add_format({'bold':True})  #第一种方式

cell_format1 = wb.add_format()  #第二种方式
cell_format1.set_bold()  #默认为加粗
cell_format1.set_font_color('blue')  #设置文本颜色为蓝色
cell_format1.set_font_size(14)    #设置就文本的颜色
cell_format1.set_align("center")  #设置对齐方式

cell_format2 = wb.add_format()   #设置格式
cell_format2.set_bg_color("#808080")   #设置背景颜色

# 创建工作表
sheet = wb.add_worksheet("newsheet")

#写入单个单元格数据
sheet.write(0,0,"2020工作表",cell_format)  #设置格式为方式一的

#合并单元格并写入
sheet.merge_range(1,0,2,2,"第一学期",cell_format1) #设置格式为方式二的

#数据
data = (
        ["一月份",500,450],
        ["二月份",500,450],
        ["三月份",500,450],
        ["四月份",500,450],
        ["五月份",500,450],
        ["六月份",500,450]
    )
#一行的数据写入
sheet.write_row(3,0,["月份","预期销售额","实际销售额"],cell_format2)  #设置背景颜色

#依次将数据写入
for index,item in enumerate(data):
    sheet.write_row(index+4,0,item)
#写入Excel公式
sheet.write(7,1,"=sum(B5:B7)")
sheet.write(8,2,"=sum(C5:C7)")

#写入超链接
sheet.write_url(9,0,"http://www.baidu.com",string="更多信息")
#插入图片
sheet.insert_image(10,0,"demo.jpeg")    


wb.close()

 使用工作簿的add_format()方法进行格式的设置,可以有两种方法,一种是使用键值对的方式

#创建格式对象
cell_format = wb.add_format({'bold':True})  #第一种方式

也可以使用内部函数的形式具体设置对应的参数

cell_format1 = wb.add_format()  #第二种方式
cell_format1.set_bold()  #默认为加粗
cell_format1.set_font_color('blue')  #设置文本颜色为蓝色
cell_format1.set_font_size(14)    #设置就文本的颜色
cell_format1.set_align("center")  #设置对齐方式

设置完成后再将格式变量添加到想要修改的单元格内容中

#写入单个单元格数据
sheet.write(0,0,"2020工作表",cell_format)  #设置格式为方式一的

#合并单元格并写入
sheet.merge_range(1,0,2,2,"第一学期",cell_format1) #设置格式为方式二的

 

posted @ 2022-09-29 15:15  Crown-V  阅读(333)  评论(0)    收藏  举报