一前言
环境:win10 python3.8
二 应用案例
如上要实现这样一张表格
1分析
-
不能去指定在某个位置去插入某个字段,如在a1去插入商品,a2去插入类型。不能这样做,给出字段后,要自动挨个插入
-
2 如一级字段批次信息要与它下面的二级字段相对应,二级字段占据了三列,一级字段也要占3列,且要合并
2 代码
from openpyxl import Workbook,load_workbook
from openpyxl.styles import Alignment
from loguru import logger
def new_workbook():
wb = Workbook()
return wb
def new_worksheet(wb, name):
ws = wb.create_sheet(name)
return ws
def get_workbook(file):
# 根据文件名读取一个excel文件
wb = load_workbook(file)
return wb
def get_worksheet(wb,name):
#根据name获取一个worksheet
ws = wb[name]
return ws
def save_excel(wb,file):
# 保存修改的内容到文件
wb.save(file)
# 插入一级字段和二级字段
def write_fields_to_excel(ws,first_fields,second_fields):
col = 1 #起始列的位置
for first_field in first_fields:
#依次挨个插入一级标题
ws.cell(row=1,column=col,value=first_field)
#一级标题下面有二级标题
if first_field not in second_fields:
col += 1
else:
current_second_fields = second_fields[first_field]
if current_second_fields:
current_second_fields_num = len(current_second_fields)
#按照二级标题的数量来合并对应的一级标题
ws.merge_cells(start_row=1,start_column=col, end_row=1, end_column=col+current_second_fields_num-1)
#二级标题所在的起始列
second_field_col = col
for second_filed in current_second_fields:
#插入二级标题
ws.cell(row=2,column=second_field_col, value=second_filed)
second_field_col += 1
#依照二级标题所占列的数量来确定下一个一级标题的起始列位置
col += current_second_fields_num
执行
wb = new_workbook()
ws = new_worksheet(wb,'test')
first_fields = ['商品名','商品类型','批次信息','规格',]
second_fields = {'批次信息':['批次','价格','日期'],'规格':['规格号','质量信息']}
write_fields_to_excel(ws,first_fields,second_fields)
save_excel(wb,'test.xlsx')
标签:openpyxl,python,fields,excel,second,ws,first,col,wb
From: https://www.cnblogs.com/MyRecords/p/18519149