2017-02-09 16 views
2

從Web下載電子表格後,需要使用python 2.7對5個工作表中的4個進行排序。我已經能夠拼湊代碼來下載和保存文件,然後對其進行分類。但是,我已經能夠弄清楚如何在多個工作表中循環。如何遍歷多個Excel工作表並使用Python對數據進行排序?

代碼

import os 
import os.path 
import urllib 
import xlwt 
from xlrd import open_workbook 

destination = 'C:\Users\Python' 
if os.path.exists(destination) is False: 
    os.mkdir(destination) 

urllib.urlretrieve("http://www.eia.gov/dnav/pet/xls/PET_PRI_FUT_S1_D.xls", os.path.join(destination, "test.xls")) 

target_column = 0  

book = open_workbook('test.xls') 
sheet = book.sheets()[1] 
data = [sheet.row_values(i) for i in xrange(sheet.nrows)] 
labels = data[0] # Don't sort our headers 
data = data[1:]  # Data begins on the second row 
data.sort(key=lambda x: x[target_column], reverse=True) 

bk = xlwt.Workbook() 
sheet = bk.add_sheet(sheet.name) 

for idx, label in enumerate(labels): 
    sheet.write(0, idx, label) 

for idx_r, row in enumerate(data): 
    for idx_c, value in enumerate(row): 
     sheet.write(idx_r+1, idx_c, value) 

bk.save('result.xls') 
+0

這個問題已經被問和回答。 http://stackoverflow.com/questions/22169325/read-excel-file-in-python –

+0

@MerlineXavier謝謝。 – Rsaha

回答

3

你可以通過片材,而不是抓住單個片材循環。

for sheet in book.sheets(): 

,而不是

sheet = book.sheets()[1] 
+0

謝謝。我很感激。我把該行的代碼,並試圖執行以下操作: '用於片book.sheets(): 板材在範圍(1,5):' 以便能夠循環通過特定的工作表,但它沒有工作。有沒有辦法指定一系列的工作表? – Rsaha

+0

@Rsaha Do'爲book.sheets()[1:5]中的表格:' –

+0

@AnEpicPerson非常感謝。 – Rsaha

相關問題