2017-09-04 40 views
2

您好我是python的新手,並且正在嘗試一些代碼以使我的工作更輕鬆。因此,這裏是我的代碼退出while循環,當它到達python的excel文件的末尾

counter = 0 
while True: 

    row_values = worksheet.row_slice(counter+1,start_colx=0, end_colx=4) 

    row['Dealer'] = int(row_values[0].value) 
    row['Name'] = str(row_values[1].value) 
    row['City'] = str(row_values[2].value) 

    counter += 1 

    if not row['Dealer']: 
     break 

我試圖打破while循環,當行[「經銷商」]爲空,也就是達到excel文件的末尾時。但它似乎不能以某種方式工作。它繼續給出IndexError:列表索引超出範圍。一些幫助將不勝感激。由於

您好我編輯我的代碼下面的以下內容:

counter = 0 
    while True: 
    row_values = worksheet.row_slice(counter+1,start_colx=0, end_colx=30) 
    row['gg'] = worksheet.cell_value(1+counter,1).strip() 
    if not row['gg']: 
     break 


    row['Dealer'] = int(row_values[0].value) 
    row['Name'] = str(row_values[1].value) 
    row['City'] = str(row_values[2].value) 
    counter += 1 

但錯誤還是一樣!幫助將不勝感激。

+0

[編輯]你的問題,並顯示哪些Python模塊使用的是何'row'初始化? – stovfl

+0

我使用的是xlrd模塊 – Shubzumt

回答

0

Question: break the while loop when row['Dealer'] is null, that is when the end of excel file is reached.

可以使用worksheet.nrows,例如獲取行的末尾:

import xlrd 
book = xlrd.open_workbook("myfile.xls") 
sh = book.sheet_by_index(0) 
print("Sheetname:{0} Rows:{1} Columns:{2}". 
    format(sh.name, sh.nrows, sh.ncols)) 

# Iterate all Rows 
row_value = {} 
for rx in range(sh.nrows): 
    print(sh.row(rx)) 
    row_value['Dealer'] = sh.cell_value(rowx=rx, colx=0) 
    row_value['Name'] = sh.cell_value(rowx=rx, colx=1) 
    row_value['City'] = sh.cell_value(rowx=rx, colx=2) 

    # Break before end of Rows at first Empty Cell 
    if row_value['Dealer'] == '': 
     break 
+0

感謝隊友的解決方案,但我仍然想知道爲什麼我無法打破while循環! – Shubzumt

+0

@Shubzumt:也許單元不是空的,檢查空白或不可打印的字符。 'sh.nrows'之後的單元格沒有考慮到! – stovfl

1

pandas庫是使用Excel的絕佳選擇。

用pip安裝熊貓。

pip install pandas 

安裝xlrd(使用Excel文件時需要)。

​​

從那裏你可以閱讀Excel電子表格與以下內容。

import pandas as pd 
df = pd.read_excel('your_excel.xlsx') 

df現在是一個DataFrame對象。您可以使用可用的熊貓工具分析和轉換數據。 read_excel()的完整文檔。

+0

其實你不需要專門安裝xlrd。這與熊貓點... ... – anki