如何使用 python 将工作表从一个 Excel 工作簿复制粘贴到另一个?

问题描述 投票:0回答:1

在 Excel 中,我可以手动:

  • 打开源工作簿
  • 选择我要复制的工作表
  • 单击左上角的全选按钮
  • ctrl-c
  • 打开目标工作簿
  • 使用底部的选项卡插入新工作表
  • 选择新工作表的 A1 单元格
  • ctrl-v

我有一本书和另一本书的相同副本,包括格式、颜色、边框、公式、尺寸、作品。

我需要在数千个目标工作簿上自动化此过程。

我尝试过使用 openpyxl,但我发现的所有解决方案都明确复制仅具有几个属性的单个单元格,而不是整个工作表。例如,大多数实现都忽略了列宽和行高。此外,Excel 还具有折叠行等功能...

是否有 Python 库(或其他语言的库)可以实现这一点?

python excel automation copy-paste xlwings
1个回答
0
投票

最简单的形式;

  • 打开源工作簿/工作表:- source_wb & source_sheet
  • 创建新工作簿
  • 使用 Excel 工作表复制/粘贴将指定工作表复制到新工作簿。
  • 删除创建工作簿时创建的新工作簿中的默认工作表

原始工作簿“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')

© www.soinside.com 2019 - 2024. All rights reserved.