I would like to access worksheets of a spreadsheet. I've copied the main workbook to another workbook using xlutils.copy(). But don't know the right way to access worksheets using xlwt module. My sample code:
import xlrd
import xlwt
from xlutils.copy import copy
wb1 = xlrd.open_workbook('workbook1.xls', formatting_info=True)
wb2 = copy(master_wb)
worksheet_name = 'XYZ' (worksheet_name is a iterative parameter)
worksheet = wb2.get_sheet(worksheet_name)
Could someone please tell me what's the right command line to access the existing worksheets in a workbook using xlwt module? I know we can use 'add_sheet' method to add a worksheet in the existing workbook using xlwt module.
Any help, appreciated.
Well, here is my answer. Let me take it step-by-step. Considerting previous answers, xlrd is the right module to get the worksheets.
xlrd.Book object is returned by open_workbook.
rb = open_workbook('sampleXLS.xls',formatting_info=True)
nsheets
is an attribute integer which returns the total number of sheets in the workbook.numberOfSheets=rb.nsheets
Since you have copied this to a new workbook
wb
-> basically to write things, wb to modify excelwb = copy(rb)
there are two ways to get the sheet information,
a. if you just want to read the sheets, use
sheet=rb.sheet_by_index(sheetNumber)
b. if you want to edit the sheet, use
ws = wb.get_sheet(sheetNumber)
(this is required in this context to the asked question)you know how many number of sheets in excel workbook now and how to get them individually, putting all of them together,
Sample Code:
reference: http://www.simplistix.co.uk/presentations/python-excel.pdf
The
sheets()
method is curiously absent from thexlwt.Workbook
class, so the other answer using that method will not work - onlyxlrd.book
(for reading XLS files) has asheets()
method. Because all the class attributes are private, you have to do something like this:If you don't need it to return None for a non-existent sheet then just remove the try/except block. If you want to access multiple sheets by name repeatedly it would be more efficient to put them in a dictionary, like this:
You can do
sheets = wb1.sheets()
to get a list of sheet objects, then call.name
on each to get their names. To find the index of your sheet, use