5

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')
2
  • I think you can do this using pyexcelerator.sourceforge.net. I think there was some example code inside the source tree.
    – user2665694
    Mar 30, 2011 at 3:31
  • I was evaluating xlwt + xlrd + xlutils and pyexcelerator, and turned to the former as pyexcelerator seems all but abandoned. I will take a look through it's code though to see if I can find something.
    – chefsmart
    Mar 30, 2011 at 3:42

1 Answer 1

3

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
1
  • cell referencing between sheets are not copied to the new workbook
    – deeshank
    Jan 20, 2014 at 9:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.