2

I am trying to make a program to open existing excel files, in order to read and write their contents. I am already having trouble opening files.

My code:

def open_sheet():
    excel = win32com.client.Dispatch("Excel.Application")
    wb = excel.Workbooks(r'C:\Users\<username>\Documents\<more file path>\test.xls').Open()
    ws = wb.Worksheets('abc') # there is a worksheet called abc.
    excel.Visible = True

Note: I abbreviated the file paths for brevity. The .py file and the test.xls file are in the same folder.

The error:

Traceback (most recent call last):
  File "C:\Users\<username>\Documents\<more file path>\automation code.py", line 37, in <module>
    open_sheet()
  File "C:\Users\<username>\Documents\<more file path>\automation code.py", line 33, in open_sheet
    wb = excel.Workbooks(r'C:\Users\<username>\Documents\<more file path>\test.xls').Open()
  File "C:\Users\<username>\AppData\Local\Programs\Python\Python36-32\lib\site-packages\win32com\gen_py\00020813-0000-0000-C000-000000000046x0x1x9\Workbooks.py", line 198, in __call__
    ret = self._oleobj_.InvokeTypes(0, LCID, 2, (13, 0), ((12, 1),),Index
pywintypes.com_error: (**-2147352567**, '例外が発生しました。', (0, None, None, None, 0, -2147352565), None)

Note: I am using a Japanese computer. The sentence in Japanese means 'Exception occurred'.

I tried to find out more about the error:

import win32api
win32api.FormatMessage(**-2147352567**)

Output:
'例外が発生しました。\r\n'
(The translation, I think, is: 'Exception occurred. \r\n')

I found this question. In it, the error number is the same, but their problem is the wrong sheet name. My sheet name, 'abc' really does exist in the excel file.

The following might also be useful diagnostic information. This code works (to create and open a new workbook):

def make_xl():
    o = win32com.client.Dispatch("Excel.Application")
    o.Visible = 1
    o.Workbooks.Add() # for office 97 – 95 a bit different!
    o.Cells(1,1).Value = "Hello"

Other info: Windows 10 Python 3.6 Python win is installed (pywin32 build 222)

I am new to using win32com. Please help me troubleshoot this problem.

4

1 回答 1

1

我认为您的问题来自:

wb = excel.Workbooks(r'C:\Users\<username>\Documents\<more file path>\test.xls').Open()

您的文件的路径应Open()如下所示:

wb = excel.Workbooks.Open(r'C:\Users\<username>\Documents\<more file path>\test.xls')

另请注意,第二个代码中没有 () Workbooks。这种方式对我有用。

于 2018-04-04T20:35:13.820 回答