'Run Excel File From Python' Error

2019-08-29 10:10发布

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)

4条回答
再贱就再见
2楼-- · 2019-08-29 10:42

@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
查看更多
家丑人穷心不美
3楼-- · 2019-08-29 10:43

I have tried many cases about:

  • raw path
  • using os.path.abspath
  • absolute path

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
查看更多
我想做一个坏孩纸
4楼-- · 2019-08-29 10:48

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.

查看更多
手持菜刀,她持情操
5楼-- · 2019-08-29 10:49

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

查看更多
登录 后发表回答