How to count the total number of sheets in an Excel file using Python

user4444350 picture user4444350 · Jun 20, 2018 · Viewed 16.4k times · Source

I am reading a excel file using python.

import pandas as pd
import os

xls = pd.ExcelFile('D:\DirectoryProject\Mapping.xlsx')

It has several number of data sheets which I don't know. How can I count the total number of sheets in Mapping.xlsx file using Python?

Answer

jpp picture jpp · Jun 20, 2018

openpyxl

import openpyxl

wb = openpyxl.load_workbook('file.xlsx') 
res = len(wb.sheetnames)

pandas

import pandas as pd

xl = pd.ExcelFile('file.xlsx')
res = len(xl.sheet_names)

xlrd

import xlrd

# use on_demand=True to avoid loading worksheet data into memory
wb = xlrd.open_workbook('file.xlsx', on_demand=True)
res = len(wb.sheet_names())  # or wb.nsheets