问题
hi im using the xlrd module to read an excel file. How can i rename the first worksheet of each excel file.
Thank you.
回答1:
I don't think you can modify files with either xlrd or xlwt. You can however copy the file with xlrd and then modify and write the copy with xlwt.
Here's an example adapted from here: writing to existing workbook using xlwt:
from xlutils.copy import copy
from xlrd import open_workbook
# open the file you're interested
rb = open_workbook('some_document.xlsx')
# copy it to a writable variant
wb = copy(rb)
# find the index of a sheet you wanna rename,
# let's say you wanna rename Sheet1
idx = rb.sheet_names().index('Sheet1')
# now rename the sheet in the writable copy
wb.get_sheet(idx).name = u'Renamed Sheet1'
# save the new spreadsheet
wb.save('new_some_document.xlsx')
# done
来源:https://stackoverflow.com/questions/13785306/change-name-of-an-excel-worksheet-after-reading-the-file-in-python