Accessing worksheets using xlwt 'get_sheet' method

user2001139 picture user2001139 · Jan 29, 2013 · Viewed 22.6k times · Source

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.

Answer

user2100379 picture user2100379 · Feb 22, 2013

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

[s.name for s in sheets].index(sheetname)