参考https://blog.csdn.net/weixin_45081575/article/details/124144987
实现了把多个 excel 文件合并成一个 excel,保存格式
import os
import copy
import openpyxl
from openpyxl.utils import get_column_letter as gcl
# 指定输入、输出文件路径
class SplitMultiSheet:
def get_all_sheet(self, files):
new_wb = openpyxl.Workbook()
for file in files:
wb = openpyxl.load_workbook(filename=file)
for sn in wb.sheetnames:
sheet = wb[sn]
sheet2 = new_wb.create_sheet(sn)
sheet2.sheet_properties.tabColor = sheet.sheet_properties.tabColor
# 开始处理合并单元格形式为“(<CellRange A1:A4>,),替换掉(<CellRange 和 >,)' 找到合并单元格
wm = list(sheet.merged_cells)
if len(wm) > 0:
for i in range(0, len(wm)):
cell2 = str(wm[i]).replace('(<CellRange ', '').replace('>,)', '')
sheet2.merge_cells(cell2)
#
for i, row in enumerate(sheet.iter_rows()):
sheet2.row_dimensions[i + 1].height = sheet.row_dimensions[i + 1].height
for j, cell in enumerate(row):
sheet2.column_dimensions[gcl(j + 1)].width = sheet.column_dimensions[gcl(j + 1)].width
sheet2.cell(row=i + 1, column=j + 1, value=cell.value)
# 设置单元格格式
source_cell = sheet.cell(i + 1, j + 1)
target_cell = sheet2.cell(i + 1, j + 1)
target_cell.fill = copy.copy(source_cell.fill)
if source_cell.has_style:
target_cell._style = copy.copy(source_cell._style)
target_cell.font = copy.copy(source_cell.font)
target_cell.border = copy.copy(source_cell.border)
target_cell.fill = copy.copy(source_cell.fill)
target_cell.number_format = copy.copy(source_cell.number_format)
target_cell.protection = copy.copy(source_cell.protection)
target_cell.alignment = copy.copy(source_cell.alignment)
# 第一个 Sheet 默认为 Sheet,可以选择删除
if 'Sheet' in new_wb.sheetnames:
del new_wb['Sheet']
new_wb.save(f"res.xlsx")
new_wb.close()
def main(self):
files = []
for file in os.listdir("."):
if file.endswith(".xlsx") and os.path.basename(file) != "res.xlsx":
files.append(file)
self.get_all_sheet(files)
if __name__ == '__main__':
sms = SplitMultiSheet()
sms.main()
print('Done.')