Rsaha
Rsaha

Reputation: 75

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

After downloading a spreadsheet from web and need to sort 4 of the 5 worksheets using python 2.7. I have been able to piece together code to download and save the file, and then sort it. However, I have been able to figure out how to loop through multiple sheets.

Code

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

Upvotes: 2

Views: 4196

Answers (1)

Merline Xavier
Merline Xavier

Reputation: 56

You can loop through the sheets instead of grabbing a single sheet.

for sheet in book.sheets():

instead of

sheet = book.sheets()[1]

Upvotes: 3

Related Questions