如何用python自动生成excel报表
需要的python模块(xlwt)
import xlwt
完成Workbook类的初始化
work = xlwt.Workbook(encoding=utf-8)
添加一个sheet
sheet = work.add_sheet(sheetname=主机信息表, cell_overwrite_ok=True)
在sheet里写数据
excel_data = [["主机IP", "CPU核数", "CPU平均使用量", "内存大小", "内存平均使用量", "磁盘大小", "磁盘平均使用量", "主机环境"], [10.208.10.88,0.43,31.26,11.2,862.1,31.9, 生产]]
for r, rows in enumerate(excel_data):
for c, val in enumerate(rows):
sheet.write(r, c, val)
保存数据
EMAIL_FILENAME = test.xls work.save(EMAIL_FILENAME)
支持多个sheet添加
只要在work.save()调用前增加多个work.add_sheet()即可添加多个sheet
如何改变样式?
字体: 自定义字体首先要初始化Font类, 然后按自己的需求更改对应的属性. font = Font() font.name = u’新宋体’ font.height = 20 * 12 font.bold = True font.colour_index = Style.colour_map[‘white’]
style = XFStyle() style.font = font
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m746ucAA-1608890414079)(evernotecid://2192D335-B095-4BA5-9172-52220AF59A1A/appyinxiangcom/27107146/ENResource/p11)]
使用样式, 在sheet.write()方法里面使用style
sheet.write(i, j, val, style)
背景颜色的改变也是类似的操作, 初始化对应的类, 然后在写数据的时候用上自定义的style
green_pattern = Pattern() green_pattern.pattern = Pattern.SOLID_PATTERN green_pattern.pattern_fore_colour = Style.colour_map[light_green] green_style = XFStyle() green_style.pattern = green_pattern # orange orange_pattern = Pattern() orange_pattern.pattern = Pattern.SOLID_PATTERN orange_pattern.pattern_fore_colour = Style.colour_map[orange] orange_style = XFStyle() orange_style.pattern = orange_pattern
另外, 还可以改变字体的左右对齐, 字体颜色, 字体加重, 下划线等特性, 具体操作和上面是类似的.
所有的特性类都可以在xlwt的源码Formatting.py里面找到, 有其他特殊要求, 查看源码.
