2

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

1 Answer 1

3

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

for sheet in book.sheets():

instead of

sheet = book.sheets()[1]
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. I appreciate it. I took that line of code and tried doing the following: for sheet in book.sheets(): for sheet in range(1,5): in order to be able to loop through specific worksheets but it didnt work. Is there a way to specify a range of sheets?
@Rsaha Do for sheet in book.sheets()[1:5]:
@AnEpicPerson Thank you very much.
@Rsaha Please note that sequences start at zero, and the second parameter to the slice operator refers to the index 1 less than it, for example, [1,2,3,4,5][1:5] returns [2,3,4].
@AnEpicPerson Understood. Thank you very much.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.