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

时间:2017-02-09 18:52:52

标签: python excel xlrd

从网上下载电子表格后,需要使用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')

1 个答案:

答案 0 :(得分:3)

您可以循环播放纸张而不是抓取单张纸张。

for sheet in book.sheets():

而不是

sheet = book.sheets()[1]