def copy_excel_sheet(self, source_file, source_sheet_name, target_file, target_sheet_name):
# 确保文件路径是正确的
source_file = os.path.abspath(source_file)
target_file = os.path.abspath(target_file)
# 打开源文件和目标文件
source_wb = openpyxl.load_workbook(source_file, read_only=False, keep_vba=True)
source_sheet = source_wb[source_sheet_name]
target_wb = openpyxl.Workbook()
target_sheet = target_wb.active
target_sheet.title = target_sheet_name
# 复制表格内容
for row in source_sheet.iter_rows(values_only=True):
target_sheet.append(row)
# 复制表格格式
for row in source_sheet.iter_rows():
for cell in row:
target_cell = target_sheet[cell.coordinate]
target_cell.font = openpyxl.styles.Font(
name=cell.font.name,
size=cell.font.size,
bold=cell.font.bold,
italic=cell.font.italic,
vertAlign=cell.font.vertAlign,
underline=cell.font.underline,
strike=cell.font.strike,
color=cell.font.color
)
target_cell.border = openpyxl.styles.Border(
left=cell.border.left,
right=cell.border.right,
top=cell.border.top,
bottom=cell.border.bottom,
diagonal=cell.border.diagonal,
diagonal_direction=cell.border.diagonal_direction,
outline=cell.border.outline,
vertical=cell.border.vertical,
horizontal=cell.border.horizontal
)
target_cell.fill = openpyxl.styles.PatternFill(
fill_type=cell.fill.fill_type,
start_color=cell.fill.start_color,
end_color=cell.fill.end_color
)
target_cell.number_format = cell.number_format
target_cell.alignment = openpyxl.styles.Alignment(
horizontal=cell.alignment.horizontal,
vertical=cell.alignment.vertical,
text_rotation=cell.alignment.text_rotation,
wrap_text=cell.alignment.wrap_text,
shrink_to_fit=cell.alignment.shrink_to_fit,
indent=cell.alignment.indent
)
# 复制合并单元格
for merged_range in source_sheet.merged_cells.ranges:
target_sheet.merge_cells(start_row=merged_range.min_row, start_column=merged_range.min_col,
end_row=merged_range.max_row, end_column=merged_range.max_col)
# 复制图片
for drawing in source_sheet._images:
img_data = drawing._data()
img_io = BytesIO(img_data)
img = PILImage.open(img_io)
img = Image(img)
img.anchor = drawing.anchor
target_sheet.add_image(img)
# 保存目标文件
target_wb.save(target_file)
09-10
5440