'Run Excel File From Python' Error

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)

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

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.

@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

Comments
  • Is the python code file in the directory where the data directory exists? Try giving full path of the xls file instead of relative path.
  • It is in the same directory. It must be this way. I shouldnt give the full path.
  • I know that's not what you are asking for but you should try the xlrd module instead of using win32com. Will make your life easier.
  • Can I open an excel file in EXCEL itself by using xlrd?
  • What path should I supply to that function?
  • When I use "wb = xl.Workbooks.Open(os.path.abspath(r"data\Modules.xls"))", I dont get error. But I cant see any Excel file opened. Even if I see an excel instance in task manager.
  • os.path.join(os.getcwd(), "path, "to", "your", "file.xls"))