Excel文件复制追加到另外一个Excel文件后
import re
from copy import copy
from openpyxl import load_workbook
tpl_sheet_name = 'Sheet1'
wb_tpl = load_workbook(filename=r'追加内容的Excel文件路径')
ws_tpl = wb_tpl[tpl_sheet_name]
wb = load_workbook(filename=r'被追加内容的Excel文件路径')
ws = wb.active
max_row = ws.max_row
cur_row = 0
for row in ws_tpl:
cur_row += 1
for cell in row:
try:
pos = f'{cell.column_letter}{max_row + cur_row}'
except Exception as e:
continue
ws[pos].value = cell.value
ws[pos].data_type = copy(cell.data_type)
if cell.has_style:
ws[pos].font = copy(cell.font)
ws[pos].fill = copy(cell.fill)
ws[pos].number_format = copy(cell.number_format)
ws[pos].alignment = copy(cell.alignment)
ws[pos].border = copy(cell.border)
if cell.comment:
ws[pos].comment = copy(cell.comment)
for x in ws_tpl.merged_cells.ranges:
match = re.search(r'([a-zA-Z]+)(\d+):([a-zA-Z]+)(\d+)', x.coord)
col_1, row_1, col_2, row_2 = match.groups()
new_coord = f'{col_1}{int(row_1) + max_row}:{col_2}{int(row_2) + max_row}'
ws.merge_cells(range_string=new_coord)
wb.save(r'要保留文件的路径')