如何使用xlrd、xlwt和xlutils将“现有”工作表添加到工作簿中

5 投票
1 回答
14155 浏览
提问于 2025-04-16 14:42

如果我理解得没错,Workbook的add_sheet方法是用来创建一个新的工作表(并把它添加到工作簿里)。我有一个现成的Excel模板(里面有一个格式化好的工作表,作为添加信息的基础),我想用xlutils把它复制多次,并用新的工作表名称添加到一个新的工作簿里。我该怎么做呢?我查看了代码,想找出如何把一个现有的工作表添加到一个已有的工作簿,但没找到相关的内容。

from xlrd import open_workbook
from xlutils.copy import copy
from xlwt import Workbook
rb = open_workbook('report3.xlt',formatting_info=True)
wb = copy(rb)
new_book = Workbook()
for distinct_employee in distinct_employees:
    w_sheet = wb.get_sheet(0)
    w_sheet.write(6,6,distinct_employee.name)
    # give the sheet a new name (distinct_employee.id_number)
    # add this sheet to new_book
book.save('all_employees.xls')

1 个回答

3

我发现使用copy.deepcopy可以创建工作表的副本。此外,通过使用_Workbook__worksheets这个属性,你可以设置工作簿中工作表的列表。

根据你的例子,我会写出以下代码:

from copy import deepcopy
from xlrd import open_workbook
from xlutils.copy import copy as copy
from xlwt import Workbook
rb = open_workbook('report3.xlt',formatting_info=True)
wb = copy(rb)
new_book = Workbook()

sheets = []
for distinct_employee in distinct_employees:
    w_sheet = deepcopy(wb.get_sheet(0))
    w_sheet.write(6,6,distinct_employee.name)

    # give the sheet a new name (distinct_employee.id_number)
    w_sheet.set_name(distinct_employee.name)

    # add w_sheet  to the sheet list
    sheets.append(w_sheet)

 # set the sheets of the workbook
 new_book._Workbook__worksheets = sheets

撰写回答