读取文件后更改 Excel 工作表的名称

问题描述 投票:0回答:1

我正在使用

xlrd
模块来读取 Excel 文件。如何重命名每个 Excel 文件的第一个工作表?

python excel xlrd
1个回答
3
投票

我认为您不能使用

xlrd
xlwt
修改文件。但是,您可以使用
xlrd
复制文件,然后使用
xlwt
修改并写入副本。

这是改编自此处的示例:使用 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
© www.soinside.com 2019 - 2024. All rights reserved.