打开两个excel文件

时间:2016-04-15 13:28:46

标签: python python-2.7 win32com

我试图通过win32com打开两个excel文件并尝试将工作表从一个工作簿移动到另一个工作簿,如下所示:

ScriptDirectory = os.path.dirname(__file__)  # this script dir # path
xl = Dispatch('Excel.Application')
wb_Header = xl.Workbooks.Open(ScriptDirectory+'\Report_Header.xlsx')
ws_Header = wb_Header.Sheets("Header")
wb_Report = xl.Workbooks.Open(ScriptDirectory+'\Report1.xlsx')
ws_Header.Move(before=wb_Report.Sheets("Test Cases"))
wb_Header.Close()
wb_Report.Close()
xl.Quit()

但它以错误结束:

Traceback (most recent call last):
File "C:\Workspace\ADTF_BV\Create_reports_v2.py", line 406, in <module>
    wb_Report = xl.Workbooks.Open(ScriptDirectory+'\Report1.xlsx')
File "C:\Python27\lib\site-packages\win32com\gen_py\00020813-0000-0000-C000-000000000046x0x1x7\Workbooks.py", line 78, in Open
, Converter, AddToMru, Local, CorruptLoad)
pywintypes.com_error: (-2147417851, 'the server threw an exception', None, None)`

我想也许我不能打开两个Dispatch,但是当我创建第二个Dispatch时这样:

ScriptDirectory = os.path.dirname(__file__)  # this script dir # path
xl = Dispatch('Excel.Application')
wb_Header = xl.Workbooks.Open(ScriptDirectory+'\Report_Header.xlsx')
ws_Header = wb_Header.Sheets("Header")
xl2 = Dispatch('Excel.Application')
wb_Report = xl2.Workbooks.Open(ScriptDirectory+'\Report1.xlsx')
ws_Header.Move(before=wb_Report.Sheets("Test Cases"))
wb_Header.Close()
wb_Report.Close()
xl.Quit()

它没有帮助。 当我只打开一个文件时,我工作正常。看起来它无法打开第二个。

1 个答案:

答案 0 :(得分:0)

好的,它现在有效,当我更改了代码行的顺序时,如下所示:

xl = Dispatch('Excel.Application')
wb_Header = xl.Workbooks.Open(ScriptDirectory+'\Report_Header.xlsx')
wb_Report = xl.Workbooks.Open(ScriptDirectory+'\Report1.xlsx')
ws_Header = wb_Header.Sheets("Header")
ws_Header.Copy(Before=wb_Report.Sheets("Test Cases"))