Home » excel » excel – Creating csv file from pandas dataframe as per the sheet names in file

excel – Creating csv file from pandas dataframe as per the sheet names in file

Posted by: admin May 14, 2020 Leave a comment


I have a excel file which has multiple sheets(6) in it. I am writing a python script to convert the each individual sheet into a csv file.

My input file looks like this and this is for example sheetname = class5

Name   ID

Mark   11
Tom    22
Jane   33

like this I have multiple sheets in the excel

I need to convert them in csv file having just ‘Name’ and class like this:


This one one sheet like this I have multiple sheets so what I am using is converting every sheet in dataframe like this

xls = pd.Excelfile('path_of_file'.xlsx)
df1= pd.read_excel(xlsx, 'Sheet1')
df2 = pd.read_excel(xlsx, 'Sheet2')
df3 = pd.read_excel(xlsx, 'Sheet3')

How can I make csv file called ‘class5’.csv with output as above and same for every sheet such as class6,7,8?

How to&Answers:

So, assuming from your question what you want is the contents of each sheet to be saved to a different csv, where the csv has the name column, and another column containing the name of the sheet it came from, without a header.

If that’s what you’re after, you could do:

xls = pd.read_excel('path_of_file',sheet_name = None)
for sheet_name, df in xls.items():
    df['sheet'] = sheet_name
    df[['Name','sheet']].to_csv(f'{sheet_name}.csv', header=False)

key point is the sheet_name argument of read_excel. as the commentor on your question states, leave this as None and you will get a dictionary you can iterate through