Python Excel - How to turn sheet name into sheet n

2019-09-12 12:13发布

问题:

In this program I create a sheet on the input excel file called new_sheet.

I need the sheet number of the sheet without having to look at the excel file.

How do I return the sheet number from the program?

import xlwt
import xlrd
import csv

workbook = xlrd.open_workbook('input.xls')

worksheet = workbook.add_sheet('new_sheet')

回答1:

I'm not understand well if you want count how many sheets there are in your Excel file or if you want know, gave the name of sheet at which number correspond; anyway, if you want count how many sheets there are in an Excel file you can proceed in this way:

workbook = xlrd.open_workbook('input.xls')
worksheet = workbook.add_sheet('new_sheet')

# number of sheet
print workbook.nsheets

Instead, if you want know the corresponding number of sheets from the name you can proceed in this way:

workbook = xlrd.open_workbook('input.xls', on_demand=True)
for index, sheet in enumerate(workbook.sheet_names()):
    if sheet == <name of your sheet>:
        print index

With on_demand=True, you can open file not loading automatically.

Regards