3

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 Answer 1

4

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')
Sign up to request clarification or add additional context in comments.

3 Comments

what does the f before{sheet_name} stand for or do?
@Michael that f-string in Python 3.
for those unfamiliar with pandas, pd comes from import pandas as pd

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.