2

I have an excel file with 40 sheet_names. I want to read each sheet to a different dataframe, so I can export an xlsx file for each sheet. Instead of writing all the sheet names one by one, I want to create a loop that will get all sheet names and add them as a variable in the "sheet_name" option of "pandas_read_excel"

I am trying to avoid this:

df1 = pd.read_excel(r'C:\Users\filename.xlsx', sheet_name= 'Sheet1');
df2 = pd.read_excel(r'C:\Users\filename.xlsx', sheet_name= 'Sheet2');
....
df40 = pd.read_excel(r'C:\Users\filename.xlsx', sheet_name= 'Sheet40');

thank you all guys

3

2 Answers 2

6

Specifying sheet_name as None with read_excel reads all worksheets and returns a dict of DataFrames.

import pandas as pd

file = 'C:\Users\filename.xlsx'
xl = pd.read_excel(file, sheet_name=None)
sheets = xl.keys()

for sheet in sheets:
    xl[sheet].to_excel(f"{sheet}.xlsx")
Sign up to request clarification or add additional context in comments.

3 Comments

In general should the of exec be avoided. There are often clearer, more direct ways to get the same effect. More info: stackoverflow.com/questions/1933451/…
Thanks for suggesting the resource, I missed the export part in the question anyway.
I modified the export path and it worked. Thank you
2

I think this is what you are looking for.

import pandas as pd
xlsx = pd.read_excel('file.xlsx', sheet_name=None, header=None)
for sheet in xlsx.keys(): xlsx[sheet].to_excel(sheet+'.xlsx', header=False, index=False)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.