Hi Jeff,
Thanks for the effort, but the sprucing up has to start with getting
it to run; in the last line, you meant "source_index", not "index".
Result: NameError: global name 'index' is not defined
In any case, source_index + 1 is refers to the new last sheet only
when the source sheet was originally the last.
Moreover, the last line can be replaced by
copied_sheet.set_name(new_name)
Setting the active sheet doesn't belong in this method -- the caller
may want to keep the active sheet (the activeness of which is only
manifested when a user opens the saved workbook) at the default (the
first sheet).
The method would be much more useful if it were to return a reference
to the copied sheet.
Remedying all that and adding a simple case (write a1 in the first
sheet, copy the first sheet, write a2 in the 2nd sheet) gives this
code:
8<---- cut here -----------
import copy
def copy_sheet(workbook, source_index, new_name):
'''
having a writable workbook you can now copy a sheet and append
to the end of the worksheets list.
workbook == book in use
source_index == index of sheet you want to copy (0 start)
new_name == name of new copied sheet
'''
# make a copy of desired sheet in memory
copied_sheet = copy.copy(workbook.get_sheet(source_index))
# append copy to worksheets list
workbook._Workbook__worksheets.append(copied_sheet)
# rename the new sheet
copied_sheet.set_name(new_name)
return copied_sheet
if __name__ == "__main__":
import xlwt
b = xlwt.Workbook()
s0 = b.add_sheet('s0')
s0.write(0, 0, "s0!a1")
s1 = copy_sheet(b, 0, "s1")
s1.write(1, 0, "s1!a2")
b.save("copied_sheet.xls")
8<--- cut here ---
When you look at the resulting file in Excel etc, s1 looks fine, but
s0 ... hmmm. Do you really intend the original sheet to be a
doppelganger of the new sheet? Try adding a line to write a3 in the
original sheet, just before the save. Check out what happens. Hint:
consider what other function in the copy module might be more suitable
than copy.
By the way, it's the original that's the copied_sheet, not the new
sheet. Could be confusing.
Apart from all of the above, to make it qualify to be included in
xlwt, it needs to do all that Workbook.add_sheet() does (except of
course it will copy a sheet instead of making a new sheet) -- that
includes another arg, all the validity testing, and adding an entry to
the name-to-index mapping.
HTH,
John