0

当我使用 win32.com 打开一个 excel 文件并将工作表粘贴到另一个 excel 文件中时,出现复制粘贴错误。

import win32com.client
import os

excel = win32com.client.Dispatch("Excel.Application")

w = excel.Workbooks.Open(os.path.join(os.getcwd(), "my_excel_file.xlsx"))

w.Sheets.Copy(wb.Sheets(1))

wb.SaveAs(os.path.join(os.getcwd(), "new_excel_file.xlsx"))
excel.Application.Quit()

这是我得到的错误:

pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Excel 无法将工作表插入到目标工作簿中,因为它包含的行和列比源工作簿少。要移动或复制数据到目标工作簿,您可以选择数据,然后使用复制和粘贴命令将其插入到另一个工作簿的工作表中。','xlmain11.chm',0,-2146827284),无)

4

1 回答 1

0

我能够重现您的错误,但它不是来自您提交的代码。我更改了您的原始代码以重现该错误。此外,缺少诸如“wb”变量未定义之类的信息,但您的问题是 Excel 问题,与 python 或 Windows COM 库无关。您的以下错误片段描述了您的 excel 错误是什么以及下面解释如何获取它的资源。

'Excel cannot insert the sheets into the destination workbook, because it 
contains fewer rows and columns than the source workbook. To move or copy 
the data to the destination workbook, you can select the data, and then use 
the Copy and Paste commands to insert it into the sheets of another workbook'

总之,如果您使用 Microsoft Excel 2003 版本并尝试将其保存到 2007 版本中,则会出现问题。

只需设置"wb.Sheets.Copy(w.Sheets(1))"为即可"w.Sheets.Copy(wb.Sheets(1))"解决您的问题。请参见下面的代码:

import win32com.client
import os

try:
    excel = win32com.client.Dispatch("Excel.Application")
    wb = excel.Workbooks.Add()
    w = excel.Workbooks.Open(os.path.join(os.getcwd(), "my_excel_file.xlsx"))
    w.Sheets.Copy(wb.Sheets(1))
    wb.SaveAs(os.path.join(os.getcwd(), "new_excel_file.xlsx"))
finally:
    # Release resources
    wb = None
    w = None
    excel.Application.Quit()
于 2020-05-28T03:23:12.187 回答