Reputation: 1379
When I try to open an excel file by calling EXCEL itself from python, I get error. How can I fix that?
Thanks in advance.
The code is:
from win32com.client import Dispatch
xl = Dispatch('Excel.Application')
wb = xl.Workbooks.Open(r"data\Modules.xls")
And the error is:
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Office Excel', u"'data\Modules.xls' could not be found. Check the spelling of the file name, and verify that the file location is correct.\n\nIf you are trying to open the file from your list of most recently used files, make sure that the file has not been renamed, moved, or deleted.", u'C:\Program Files (x86)\Microsoft Office\Office12\1033\XLMAIN11.CHM', 0, -2146827284), None)
Upvotes: 0
Views: 9264
Reputation: 1
The path to excel file should be absolute and py file, excel file should be in different folder. I was also getting the same error when I used above measures problem got solved. In case of relative path you need to convert it to absolute.
Upvotes: 0
Reputation: 13
@Shanshal I don't know if you are still looking for the answer After opening the excel if you can't see the file, write the below code
xl.Visible = True
Upvotes: 0
Reputation: 14318
I have tried many cases about:
the following is the result:
(1)Failed Cases:
#[1] Fail
# xlsPath = "chart_demo.xls";
# wb = xl.Workbooks.open(xlsPath); #pywintypes.com_error
#[2] Fail
# xlsPath = "D:\tmp\tmp_dev_root\python\excel_chart\chart_demo.xls";
# absPath = os.path.abspath(xlsPath);
# print "absPath=",absPath; #absPath= D:\tmp\tmp_dev_root\python\excel_chart\ mp mp_dev_root\python\excel_chart\chart_demo.xls
# wb = xl.Workbooks.open(absPath); #pywintypes.com_error
#[3] Fail
# xlsPath = "D:\tmp\tmp_dev_root\python\excel_chart\chart_demo.xls";
# normalPath = os.path.normpath(xlsPath);
# print "normalPath=",normalPath; #normalPath= D: mp mp_dev_root\python\excel_chart\chart_demo.xls
# wb = xl.Workbooks.open(normalPath); #pywintypes.com_error
#[4] Fail
# rawPath = r"chart_demo.xls";
# wb = xl.Workbooks.open(rawPath); #pywintypes.com_error
(2)Successfull Cases:
#[5] OK
# xlsPath = "chart_demo.xls";
# absPath = os.path.abspath(xlsPath);
# print "absPath=",absPath; #absPath= D:\tmp\tmp_dev_root\python\excel_chart\chart_demo.xls
# wb = xl.Workbooks.open(absPath); #OK
#[6] OK
# rawPath = r"D:\tmp\tmp_dev_root\python\excel_chart\chart_demo.xls";
# wb = xl.Workbooks.open(rawPath); # OK
Upvotes: 0
Reputation: 987
I believe the reason why you must specify a full path to the file is because you are interacting with Excel through a COM interface. This is not the same as calling CreateProcess. The COM interface tells excel to open a file, however, the path is passed in relation to the working directory of the excel.exe process.
Upvotes: 0
Reputation: 83758
Use os.path.abspath() to convert file system paths to absolute. The current working directory of yout Python and Excel process is not the same.
http://docs.python.org/library/os.path.html
Upvotes: 9