user4444350
user4444350

Reputation:

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

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?

Upvotes: 27

Views: 51901

Answers (2)

Sankar
Sankar

Reputation: 586

Just to add to the previous answer -

len(pd.read_excel(r"D:\DirectoryProject\Mapping.xlsx", sheet_name="None"))

This way you can get the number of sheets as well.

Upvotes: 2

jpp
jpp

Reputation: 164773

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

Upvotes: 65

Related Questions