tbcloud
tbcloud

Reputation: 35

Using pywin32 to find an Excel Workbook

I have downloaded and installed pywin32. I am trying to open a workbook using pywin32 and I am almost positive I am coding this correctly, but I am coming up with an error like this.

   File "<COMObject <unknown>>", line 8, in Open
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"'Kithenshiftweekly.xlsx' 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'xlmain11.chm', 0, -2146827284), None)

My current code is the following (not very much)

import win32com.client
x1 = win32com.client.Dispatch("Excel.Application")
x1.Visible = True
x1.Workbooks.Open("Kitchen")

x1.Workbooks.Open("Kitchen") causes this problem.

this doesn't find the work book though. Whats happening?

Upvotes: 0

Views: 3847

Answers (1)

user2986898
user2986898

Reputation: 433

There are two problems; first, you have to append the extension (like "Kitchen.xlsx") and second, you have to give the full path to the workbook. So if your workbook is "Kitchen.xlsx" and you have your script in the same folder then your code should look something like this:

import win32com.client
import os
x1 = win32com.client.Dispatch("Excel.Application")
x1.Visible = True
x1.Workbooks.Open(os.path.join(os.getcwd(), "Kitchen.xlsx"))

(The os.getcwd() returns the full path to the directory of your script. If you want to store your code and workbook in different directories, then you can specify the path by a string. Print os.getcwd() to see how to do that.)

Upvotes: 1

Related Questions