如何循环通过多个Excel工作表和使用pythonsorting数据?

从网上下载电子表格后,需要使用python 2.7对5个工作表中的4个进行sorting。 我已经能够拼凑代码来下载和保存文件,然后对其进行分类。 但是,我已经能够弄清楚如何循环多个工作表。

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') 

您可以循环浏览表格,而不是抓取单张表格。

 for sheet in book.sheets(): 

代替

 sheet = book.sheets()[1]