Python xlwt模块写Excel问题集合

1、数字转换成汉字

数据库查询返回结果为多元组,在写入Excel需要判断,数据库查询结果是否为数字,为数字的话需要将其转换成对应的汉字,此时元组不可修改,所以需要将返回结果修改成列表。实现可以在数据库查询返回结果时,就将返回结果改成list类型。注:这是在Python3下适用。

 

res = list(map(list, cur.fetchall()))
return res

 

 

2、在写Excel时,时间写入Excel相关问题。

数据库查询的返回的时间格式为:datetime.datetime(2019, 10, 28, 19, 41, 17),输出为:2019-10-28 19:41:17。

但是在写入Excel后,变成了43766.8203356481,此时需要带格式写入。

 

style = xlwt.XFStyle()     # 初始化样式
style.num_format_str = 'YYYY-MM-DD hh:mm:ss'    # 设置样式
sheet.write(0, 3, datetime.datetime(2019, 10, 28, 19, 50, 55),style)  # 带样式写入
    

 

3、在写Excel时,标题写入Excel加粗相关问题。

style = xlwt.XFStyle()   # 初始化样式
font = xlwt.Font()       # 为样式创建字体
font.bold= True          # 设定样式
style.font = font
sheet.write(0, i, header,style)     # 带样式写入

 

猜你喜欢

转载自www.cnblogs.com/deliaries/p/11799759.html