想要使用Python Wincom32从工作簿中读取工作表

时间:2014-09-19 05:19:37

标签: python excel

我想使用Python Wincom32模块从工作簿中读取工作表,但如果工作表数量更多,则无法读取它。 例如,我有一个excel工作簿,其中包含总共150个工作表,我正在尝试使用Python Wincom32模块阅读第89个Excel工作表,但它给了我一些工作表名称,这在Excel工作簿中根本不存在。 我使用下面的python代码

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 个答案:

答案 0 :(得分:0)

您的代码中存在一些错误:
1)而excel.visible = 1应为excel.Visible = 1
2)而是excel.Workbooks.open('<PATH TO EXCEL>') - excel.Workbooks.Open('<PATH TO EXCEL>')
3)而是wb.Sheets.count - wb.Sheets.Count
4)而是wb.Sheets[ 89 ].name - wb.Sheets[ 89 ].Name

这是固定版本(适合我):

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