How to add "existing" worksheet to a workbook using xlrd, xlwt and xlutils

chefsmart picture chefsmart · Mar 30, 2011 · Viewed 12.9k times · Source

If I understand correctly, a Workbook's add_sheet method creates a new worksheet (and adds it to the workbook). 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. 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')

Answer

ignacio.munizaga picture ignacio.munizaga · Jan 14, 2013

I found out that with copy.deepcopy you can create a copy of your woorksheets. Also using the _Workbook__worksheets attribute you can set the list of sheets of your workbook

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