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

5

如果我理解正确,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')

我认为你可以使用http://pyexcelerator.sourceforge.net/来完成这个任务。我想源代码树中有一些示例代码。 - user2665694
我正在评估xlwt + xlrd + xlutils和pyexcelerator,由于pyexcelerator似乎已经被放弃,所以我转向了前者。不过我会浏览一下pyexcelerator的代码,看看能否找到有用的东西。 - chefsmart
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

单元格在工作表之间的引用未被复制到新工作簿中。 - deeshank

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接