如何循环遍历多个 excel 工作表并使用 python 对数据进行排序?

How to loop through multiple excel worksheets and sort data using python?

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

代码

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

您可以遍历 sheet 而不是抓取单个 sheet。

for sheet in book.sheets():

而不是

sheet = book.sheets()[1]