需求:生成一个excel文件,但是表头有许多内容需要合并单元格,那个表头的内容又相当多。于是就自己写了一个方法,方便写入表头。
from openpyxl.workbook import Workbook
from openpyxl.writer.excel import ExcelWriter
from openpyxl.reader.excel import load_workbook
from openpyxl.styles import Alignment
from zipfile import ZipFile, ZIP_DEFLATED
def write_hear(ws, hear, start_row, end_row, i):
"""
写入表头
:param ws: worksheet
:param hear: 表头
:param start_row: 开始-行
:param end_row: 结束-行
:param i: 列
:return: 无
"""
alignment_center = Alignment(horizontal='center', vertical='center')
for item in hear:
if width := item.get('width'):
ws.merge_cells(start_row=start_row, start_column=i, end_row=start_row, end_column=i + width - 1)
ws.cell(row=start_row, column=i, value=item['label']).alignment = alignment_center
write_hear(ws, item['children'], start_row+1, end_row, i)
i = i + width
else:
ws.merge_cells(start_row=start_row, start_column=i, end_row=end_row, end_column=i)
ws.cell(row=start_row, column=i, value=item['label']).alignment = alignment_center
i = i + 1
def write_data(ws, start_row, records):
"""
数据写入表格
:param ws:
:param start_row:
:param records: 内容数据,二维数组[][]
:return: 无
"""
i = start_row + 1
for record in records:
for x in range(1, len(record) + 1):
ws.cell(i, x, record[x-1])
i += 1
def write_excel_new(hear, hear_row, records, sheet_name='Sheet1', save_excel_name='save.xlsx'):
"""
生成xlsx文件
:param hear: 表头内容
:param hear_row: 表头占的行数
:param records: 内容
:param sheet_name: 标题
:param save_excel_name: 文件名
:return: 无
"""
wb = Workbook()
archive = ZipFile(save_excel_name, 'w', ZIP_DEFLATED)
ew = ExcelWriter(workbook=wb, archive=archive)
ws = wb.worksheets[0]
ws.title = sheet_name
ws.column_dimensions.width = 20
write_hear(ws, hear, 1, hear_row, 1)
# write_data(ws, hear_row, records)
ew.save()
hear_ = [
{'label': '所属班组'},
{'label': '电压等级(kV)'},
{'label': '线路名称'},
{'label': '出线站'},
{'label': '进线站'},
{'label': '调度编号'},
{'label': '色标'},
{
'label': '线路长度(km)', 'width': 5,
'children': [
{'label': '单回路'},
{'label': '双回路'},
{'label': '三回路'},
{'label': '四回路及以上'},
{'label': '总长度'}
]
},
{
'label': '杆塔数量(基)', 'width': 7,
'children': [
{'label': '水泥杆'},
{
'label': '铁塔', 'width': 3,
'children': [
{'label': '钢管杆'},
{'label': '角钢塔'},
{'label': '钢管组合塔'},
]
},
{'label': '直线'},
{'label': '耐张'},
{'label': '总数'},
]
},
{
'label': '杆塔物理数量统计(基)', 'width': 4,
'children': [
{'label': '单回路'},
{'label': '双回路'},
{'label': '三回路'},
{'label': '四回路及以上'}
]
},
{
'label': '导地线型号', 'width': 3,
'children': [
{'label': '导线型号'},
{
'label': '地线型号', 'width': 2,
'children': [
{'label': '左地线'},
{'label': '右地线'},
]
}
]
},
{'label': '投产日期'},
{'label': '备注'},
{'label': '有无摄像头'}
]
if __name__ == '__main__':
write_excel_new(hear_, 3, None)
hear_:是我定义的一个表头字典。
write_hear:把**hear_**字典生成表头,至于行宽什么的看着设置。
write_data:写入数据,在上面的代码里,我注释掉了,所以传Node。
要是还有什么需求,可以找官网第三方库openpyxl
的官网