Want to read Worksheets from a workbook using Python Wincom32

Question:

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
Asked By: pankmish

||

Answers:

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.countwb.Sheets.Count,
  4. instead wb.Sheets[ 89 ].namewb.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

print ws_name
Answered By: NorthCat
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.