Python Excel - How to turn sheet name into sheet number

喜欢而已 提交于 2019-12-12 03:06:25

问题


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



来源:https://stackoverflow.com/questions/38063661/python-excel-how-to-turn-sheet-name-into-sheet-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!