Converting Excel file with multiple sheets into multiple csv files using Jupyter notebook

Viewed 2485

I have an excel file that contains multiple sheets. I want to convert these sheets into separate CSV files.

I tried this code and got an ordered dictionary of the sheets. Now I need to save them as CSV files in one step, instead of having to save each one manually in a separate step

xls = pd.ExcelFile('file.xlsx')
sheets = {}
for sheet_name in xls.sheet_names:
    sheets[sheet_name] = xls.parse(sheet_name)
1 Answers

You can use to_csv to save dataframe as csv file:

# I prefer reading excel with pd.read_excel
# passing `sheet_name=None` returns a dictionary 
# with the form {sheet_name: dataframe}
data = pd.read_excel('file.xlsx', sheet_name=None)

# loop through the dictionary and save csv
for sheet_name, df in data.items():
    df.to_csv(f'{sheet_name}.csv')
Related