Copying with xlutils using a sheet name not sheet index

1,755 views
Skip to first unread message

Miles Grogger

unread,
Jul 25, 2013, 1:13:28 PM7/25/13
to python...@googlegroups.com
I answered my question about xlrd/xlwt copying by using xlutils. xlutils is great. It does exactly what I was looking for, with one small problem. Actually it's not such a small problem after all. Whenever I attempt to substitute the "rs = rb.sheet_by_index("#")" line for "rs = rb.sheet_by_name("name")" the line, "ws = wb.get_sheet("")" does not work and produces the error, "list indices must be integers, not str". Normally, I would not mind doing a bit more work and looking up the index of the worksheets that need to be extracted, however the nature of my project is such that it is prudent to use the worksheet names and not the indices.  If anyone can help that would be great. Attached is an image of my code and the error.

Miles
Screen Shot 2013-07-25 at 12.12.48 PM.png

John Yeung

unread,
Jul 25, 2013, 10:13:27 PM7/25/13
to python-excel
Since you're new, I will give you some basics:

Let's say you have a list (any Python list). You can get the index
number from the value:

>>> fruits = ['apple', 'banana', 'pear']
>>> fruits[2]
'pear'
>>> fruits.index('pear')
2

So, applying this to xlrd, get a list of the sheet names using the
sheet_names() method. Get the index number using the index() method.
Assuming you have rb and wb already:

>>> rb_sheet_names = rb.sheet_names()
>>> my_sheet_index = rb_sheet_names.index('my_sheet')
>>> ws = wb.get_sheet(my_sheet_index)

You don't have to be as verbose as that, but I was trying to make it
as easy to follow as I could. If you like, you can combine the above
lines:

>>> ws = wb.get_sheet(rb.sheet_names().index('my_sheet'))

John Y.

Miles Grogger

unread,
Jul 26, 2013, 11:33:23 AM7/26/13
to python...@googlegroups.com
Thanks John, that helped a lot. I have a running code now which is allowing me to take an existing workbook, copy it, and save the copy as a new workbook in a separate folder. However, I want to be able to take just one worksheet from an existing workbook and save only that worksheet into a new workbook. I have tried several different options such as only copying the worksheet which was impossible because "'Sheet' object has no attribute 'datemode'", as well as trying to save just the worksheet. It made sense that the latter wouldn't work since even excel won't let you save individual worksheets unless they are made in new workbooks, but I'm still unclear as to why the former wouldn't work, seeing as though excel allows you to copy a worksheet and place it in a separate workbook. Any help would be great.

Thanks, 
MiIes
Reply all
Reply to author
Forward
0 new messages