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

如果我理解正确,工作簿的add_sheet方法创build一个新的工作表(并将其添加到工作簿)。 我有一个现有的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') 

我发现用copy.deepcopy你可以创build你的woorksheets的副本。 同样使用_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