简体   繁体   English

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

[英]How to add “existing” worksheet to a workbook using xlrd, xlwt and xlutils

If I understand correctly, a Workbook's add_sheet method creates a new worksheet (and adds it to the workbook). 如果我理解正确,Workbook的add_sheet方法会创建一个新的工作表(并将其添加到工作簿)。 I have an existing excel template (with one formatted sheet that serves as a base to add information to) that I would like to copy using xlutils and add it to a new Workbook multiple times using new sheet names. 我有一个现有的Excel模板(有一个格式化的工作表作为添加信息的基础)我想用xlutils复制并使用新工作表名称多次将其添加到新工作簿。 How do I go about achieving this? 我该如何实现这一目标? I went through the code to find out how to add an existing worksheet to an existing workbook, but couldn't find anything like that? 我通过代码了解如何将现有工作表添加到现有工作簿,但找不到类似的东西?

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')

I found out that with copy.deepcopy you can create a copy of your woorksheets. 我发现使用copy.deepcopy你可以创建一个woorksheets的副本。 Also using the _Workbook__worksheets attribute you can set the list of sheets of your workbook 同样使用_Workbook__worksheets属性,您可以设置工作簿的工作表列表

Using your example I would have the following code: 使用您的示例我将得到以下代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM