wisenhiemer
wisenhiemer

Reputation: 155

Print just the sheetnames with Python

How can I print just the sheet names. I using a loop that gets the sheets from range 2 to 9 and prints but I would like to remove the label around it and just print the name of the sheet.

import glob
import openpyxl

path = 'C:/ExcelFolder/*.xlsx'
files = glob.glob(path)

for file in files:
wb = openpyxl.load_workbook(file)

for n in range(2, 9):
    SheetName = wb.worksheets[n]
    print(SheetName)

Output example:

<Worksheet "Monday">
<Worksheet "Tuesday">
<Worksheet "Wednesday">
<Worksheet "Thursday">
<Worksheet "Friday">
<Worksheet "Saturday">

Upvotes: 0

Views: 17192

Answers (5)

Adam Safier
Adam Safier

Reputation: 36

Since you are using openpyxl

from openpyxl import load_workbook
ar_source = 'My_file"
workbook = load_workbook(filename=ar_source)
tabs = workbook.sheetnames
print ('Workbook: ',tabs)
for tab in tabs:
    print (tab)

My test output lists each sheet (tab at the bottom) in the entire workbook:

Workbook:  ['Review SC', 'Review AV', 'AR Language', 'ISD', 'Legend']
Review SC
Review AV
AR Language
ISD
Legend

Upvotes: 0

CRBelhekar
CRBelhekar

Reputation: 379

If you are using pandas read_excel method.
You can retrieve the sheet names using the dictionaries keys method, as sheet names are stored in dictionaries.

xls = pd.read_excel(url, sheet_name = None)
print(xls.keys())

Upvotes: 10

mcbridecaleb
mcbridecaleb

Reputation: 101

Two methods. The first is similar to the answer by @Gopal Choudhary

For a .xlsx, you could use glob and openpyxl.

path = 'C:path/*.xlsx'
files = glob.iglob(path)
for fileName in files:
    wb = openpyxl.load_workbook(fileName)
    w = wb.sheetnames
    for sheetname in w:
        print(sheetname)

For a .xls you could use pandas.

sheet_to_df_map = pd.read_excel('file_name', sheet_name=None)

Upvotes: 0

Gopal Choudhary
Gopal Choudhary

Reputation: 19

from openpyxl.reader.excel import load_workbook
import glob

path = '*.xlsx'
files = glob.iglob(path)
for fileName in files:
    wb=load_workbook(fileName)
    w = wb.sheetnames
    for sheetname in w:
        print sheetname

Upvotes: 0

Charlie Clark
Charlie Clark

Reputation: 19537

How about: print(wb.sheetnames)

Upvotes: 7

Related Questions