Search code examples
pythonpython-2.7win32com

Open two excel files


I'm trying to open two excel files via win32com and trying to move a sheet from one workbook to another, like this:

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()

But it ends with an error:

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)`

I thought maybe I cannot open two Dispatch, but when I create second Dispatch like this:

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()

it doesn't help. I works ok when I open only one file. It looks like it can't deal with opening the second one.


Solution

  • OK, it works now, when I changed an order of code lines, like this:

    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"))