在 Excel 中,我可以手动:
我有一本书和另一本书的相同副本,包括格式、颜色、边框、公式、尺寸、作品。
我需要在数千个目标工作簿上自动化此过程。
我尝试过使用 openpyxl,但我发现的所有解决方案都明确复制仅具有几个属性的单个单元格,而不是整个工作表。例如,大多数实现都忽略了列宽和行高。此外,Excel 还具有折叠行等功能...
是否有 Python 库(或其他语言的库)可以实现这一点?
最简单的形式;
原始工作簿“source_wb”保留原始工作表,因为该工作簿在此代码示例中未更改(或保存)。
当然,您可以在复制工作表时从源工作簿中删除工作表,并在需要时在最后保存源工作簿。或者,如果复制了所有必需的工作表后不再需要源工作簿,只需删除源工作簿即可。
import xlwings as xw
source_wb = 'foo.xlsx'
source_sheet = 'Sheet1'
with xw.App(visible=False) as app:
### Source Workbook and Sheet
wb_source = xw.Book(source_wb)
ws_source = wb_source.sheets[source_sheet]
### Create new workbook to copy Sheet to
wb_dest = xw.Book()
ws_dest_default = wb_dest.sheets.active
# Need for Sheet position but will be deleted after
ws_dest_default.name = "tobedeleted" # A name that should not clash with sheets in the source workbook
### Move Sheets to new work book and Delete the "tobedeleted" default Sheet
ws_source.copy(after=ws_dest_default) # or 'before'can be used, doesn't matter the default sheet is deleted
ws_dest_default.delete() # Remove the default Sheet from the new workbook
### Save the new workbook
wb_dest.save('NewWorkBook.xlsx')