change name of an excel worksheet after reading the file in python

て烟熏妆下的殇ゞ 提交于 2019-12-23 05:06:44

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!