2014-09-19 46 views
2

我想使用Python Wincom32模塊從工作簿中讀取工作表,但如果工作表數量更多,則無法讀取它。 例如,我有一個Excel工作簿,共有150個工作表,我正在嘗試使用Python Wincom32模塊閱讀第89個Excel工作表,但它給了我一些Excel工作簿中不存在的工作表名稱。 我使用下面的Python代碼想要使用Python讀取工作簿中的工作表Wincom32

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

你的代碼適合我。你確定你的wb有150張工作表嗎? count變量打印什麼? – sk11 2014-09-19 06:23:37

+0

你確定你正在打開正確的工作簿嗎?如果它提供了一些工作簿中不存在的工作表名稱,則必須來自_somewhere_;我不認爲Excel正在編寫數據,因爲你抓住它玩遊戲,並打開老闆屏幕。 – abarnert 2014-09-19 08:37:19

+0

@ sk11我的工作簿有150張工作表,count變量給出了輸出爲excel文件中存在的工作表總數。 – pankmish 2014-09-19 09:25:54

回答

0

有在你的代碼中的錯誤:
1),而不是excel.visible = 1excel.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

這是固定版本(wor ks對我來說):

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 
+0

您是否嘗試過在單個工作簿中使用超過85個工作表的上述代碼;因爲我在閱讀工作表名稱時遇到問題,如果我在** ws_name = wb.Sheets [89] .Name **中輸入超過85的值。 – pankmish 2014-09-19 09:51:44

+0

是的,我試了一下,效果很好。你可以給你的Excel文件的鏈接? – NorthCat 2014-09-19 10:02:20

+0

現在它爲我工作;這個python代碼也可以工作,不需要在你的答案中提到你的代碼。 – pankmish 2014-09-19 14:01:05

相關問題