查看openpyxl.copy_worksheet 的代码看为啥不支持跨工作簿
只找到了设置的断言:
openpyxl.worksheet.copier.WorksheetCopy :line 32
if self.source.parent != self.target.parent:
raise ValueError('Cannot copy between worksheets from different workbooks')
没发现什么必须同工作簿的操作(水平有限,没看出问题)
所以怀疑是故意不让跨工作簿copy而不是无法复制。
测试结果是没有复制插入的图片,不知道不做更改同工作簿复制会不会这样。
再在这个基础上更改有点麻烦,另外感觉整个操作没必要写成类。
def copySheet(source, target):
# 抄写两个断言,一个保证输入对象类型正确
if (not isinstance(source, Worksheet)
and not isinstance(target, Worksheet)):
raise TypeError("Can only copy worksheets")
# 一个保证不是自己复制自己
if source is target:
raise ValueError("Cannot copy a worksheet to itself")
# 复制单元格子数据
for (row, col), source_cell in source._cells.items():
target_cell = target.cell(column=col, row=row)
# 复制数值和数据类型
target_cell._value = source_cell._value
target_cell.data_type = source_cell.data_type
# 复制单元格样式
if source_cell.has_style:
target_cell._style = copy(source_cell._style)
# 复制单元格超链接
if source_cell.hyperlink:
target_cell._hyperlink = copy(source_cell.hyperlink)
# 复制单元格注释批注
if source_cell.comment:
target_cell.comment = copy(source_cell.comment)
# 追加:拷贝插入的图片
target._images = source._images
# 复制行高列宽等信息
for attr in ('row_dimensions', 'column_dimensions'):
src = getattr(source, attr)
dst = getattr(target, attr)
for key, dim in src.items():
dst[key] = copy(dim)
dst[key].worksheet = target
# 这一堆是啥不知道
target.sheet_format = copy(source.sheet_format)
target.sheet_properties = copy(source.sheet_properties)
target.merged_cells = copy(source.merged_cells)
target.page_margins = copy(source.page_margins)
target.page_setup = copy(source.page_setup)
target.print_options = copy(source.print_options)
借用 openpyxl.Workbook.copy_worksheet
openpyxl/workbook/workbook.py : line 431
本方法依然需要先在 目的工作簿上创建一个sheet
wb0 = load_workbook("src.xlsx")
wb1 = Workbook()
new_title = "new_sheet_title"
to_worksheet = wb1.create_sheet(title=new_title)
copySheet(wb0["src_sheet_title"], to_worksheet)