Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pywintypes.com_error in Python during Excel import

I get this error on running my module gasprop. I do not understand what the error means and how to fix it:

import gasprop
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "gasprop.py", line 13, in <module>
sheet = wb.Sheets("Input1")
File "C:\Python27\lib\site-packages\win32com\gen_py\00020813-0000-0000-C000-000000000046x0x1x6\Sheets.py", line 113, in __call__
ret = self._oleobj_.InvokeTypes(0, LCID, 2, (9, 0), ((12, 1),),Index
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)

And here is my module gasprop:

import win32com.client, os
xl = win32com.client.gencache.EnsureDispatch("Excel.Application")
thisdir = os.getcwd()
wb = xl.Workbooks.Open(thisdir+"/Input1.xlsx")
sheet = wb.Sheets("Input1")

......

def megaverify(self):
    listtr,listp=[],[]
    for i in range(16):
        tr=float(sheet.Range("D"+str(5+i)).Value)
        p=float(sheet.Range("C"+str(5+i)).Value)
        listtr.append(tr);listp.append(p)

    return tr, p
like image 636
Pearl Philip Avatar asked Jan 11 '23 09:01

Pearl Philip


2 Answers

You can use this teсhnique to get more information about error:

import win32api
e_msg = win32api.FormatMessage(-2147352565)
print e_msg.decode('CP1251')

The message you get means that your excel file does not have a sheet with the name "Input1". You can simply rename it.

like image 103
NorthCat Avatar answered Jan 17 '23 18:01

NorthCat


The error occurred because the sheet I wanted to call from the excel workbook did not match the name I was referencing it by in my python code. My sheet was actually Sheet1 (by default in excel) but I was calling a sheet Input1 as seen in line 5 of my module gasprop. The mismatch in names caused this error.

like image 43
Pearl Philip Avatar answered Jan 17 '23 18:01

Pearl Philip