2
votes

I want to read Worksheets from a workbook using Python Wincom32 module but not able to read it if number of sheets are more. For Example i have an excel workbook with total 150 worksheets in it and i am trying to read 89th Excel worksheet using Python Wincom32 module but it is giving me some sheet name which is not present in the Excel Workbook at all. I am using below python code

import win32com.client
dispatch = win32com.client.Dispatch
excel = dispatch("Excel.Application")
excel.visible = 1
wb = excel.Workbooks.open('<PATH TO EXCEL>')
count = wb.Sheets.count # count stores total number of worksheets present
print count  
ws_name = wb.Sheets[ 89 ].name 
""" This is supposed to read the name of 89th Worksheet instead it is giving me some garbage
    name  """
print ws_name
1
Your code works fine for me. Are you sure your wb has 150 worksheets? What does the count variable prints? - sk11
Are you sure you're opening the right workbook? If it's giving you some sheet name that isn't present in the workbook, that must be coming from somewhere; I don't think Excel is making up data because you caught it playing games and it turned on the boss screen. - abarnert
@sk11 my workbook is having 150 worksheets, count variable gives me the output as total number of worksheets present in the excel file. - pankmish

1 Answers

1
votes

There are some mistakes in your code:
1) instead excel.visible = 1 should be excel.Visible = 1,
2) instead excel.Workbooks.open('<PATH TO EXCEL>') - excel.Workbooks.Open('<PATH TO EXCEL>')
3) instead wb.Sheets.count - wb.Sheets.Count,
4) instead wb.Sheets[ 89 ].name - wb.Sheets[ 89 ].Name

This is fixed version (works for me):

import win32com.client
dispatch = win32com.client.Dispatch
excel = dispatch("Excel.Application")
excel.Visible = 1
wb = excel.Workbooks.Open('<PATH TO EXCEL>)
count = wb.Sheets.Count # count stores total number of worksheets present
print count
ws_name = wb.Sheets[ 89 ].Name
""" This is supposed to read the name of 89th Worksheet instead it is giving me some garbage
    name  """
print ws_name