背景
测试哥哥最近需要生成一系列数据相关的报表类测试报告。那么最方便的就是在Excel中直接填写啦!
如下图为某次机器学习测试的结果。
面对这样的结果,一个还好,如果你需要填写多个,那就很费劲了。
比如在持续集成过程中,每版本来填写一个excel呢?
经过对比,主编心中使用Python操作Excel最方便的库是openpyxl!
python可以进行Excel操作的还有xlrd,xlwt,pandas,优缺点如下:
openpyxl
安装
pip install openpyxl
创建文件
from openpyxl import Workbook
wb = Workbook()
#创建Excel对象
sheet操作
1.获得当前sheet对象
ws = wb.active
#创建sheet对象为当前活动格
2.sheet改名
ws.title = '机器学习sheet'
3.新建sheet
ws = wb.create_sheet('新建了一个新的sheet')
4.删除sheet
wb.remove(ws)
单元格操作
1.填入内容
ws['A1'].value = '123'
2.合并单元格
ws.merge_cells('A1:A2')
Tips
openpyxl跟Excel单元格的行列保持一致,不再追求极客(不从0开始),因此你可以大胆在Excel中找到对应的行标来操作。
如上面的操作结果:
单元格样式
from openpyxl.styles import PatternFill, Alignment, Border, Side, Font
sheet = ws['A1']
sheet.fill = PatternFill("solid", fgColor='FF000000')
#颜色代码:http://www.114la.com/other/rgb.htm
#设置数据垂直居中和水平居中
sheet.alignment = Alignment(horizontal='center', vertical='center')#, wrap_text=True)
border = Border(left=Side(style='thin', color='FF000000'), right=Side(style='thin', color='FF000000'),
top=Side(style='thin', color='FF000000'), bottom=Side(style='thin', color='FF000000'),
diagonal=Side(style='thin', color='FF000000'), diagonal_direction=0,
outline=Side(style='thin', color='FF000000'), vertical=Side(style='thin', color='FF000000'),]
horizontal=Side(style='thin', color='FF000000'))
sheet.border = border
即可实现设置颜色和居中
保存
wb.save('路径')
完整代码示例见下
from openpyxl import Workbook
from openpyxl.styles import PatternFill, Alignment, Border, Side, Font
def excel单元格填入(sheet, value, color="FF8C69"):
sheet.value = value
sheet.fill = PatternFill("solid", fgColor=color) # 颜色代码:http://www.114la.com/other/rgb.htm
# 设置数据垂直居中和水平居中
sheet.alignment = Alignment(horizontal='center', vertical='center')#, wrap_text=True)
border = Border(left=Side(style='thin', color='FF000000'), right=Side(style='thin', color='FF000000'),
top=Side(style='thin', color='FF000000'), bottom=Side(style='thin', color='FF000000'),
diagonal=Side(style='thin', color='FF000000'), diagonal_direction=0,
outline=Side(style='thin', color='FF000000'), vertical=Side(style='thin', color='FF000000'),
horizontal=Side(style='thin', color='FF000000'))
sheet.border = border
wb = Workbook()
ws = wb.active
ws.title = '机器学习sheet'
ws = wb.create_sheet('新建了一个新的sheet')
excel单元格填入(ws['A1'], '机器学习测试结论')
ws.merge_cells('A1:B1')
data = {
'样本数':207684,
'分类正确':207386,
'准确率':99.8,
'错误率':0.14,
'正例':1300,
'反例':200000,
'精确率':99.123,
'召回率':90.456
}
i = 2
for k, v in data.items():
excel单元格填入(ws['A' + str(i)], k, 'FFFFFF')
excel单元格填入(ws['B' + str(i)], v, 'FFFFFF')
i += 1
wb.save('机器学习测试.xlsx')
操作结果
文章评论(0)