Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write CSV files into XLSX using Python Pandas?

I have several .csv files and I want to write them into one .xlsx file as spreadsheets.

I've loaded these .csv files into Pandas.DataFrame using following code:

df1 = pandas.read_csv('my_file1.csv')
df2 = pandas.read_csv('my_file2.csv')
......
df5 = pandas.read_csv('my_file5.csv')

But I couldn't find any functions in Pandas that can write these DataFrames into one .xlsx file as separated spreadsheets.

Can anyone help me with this?

like image 596
ChangeMyName Avatar asked Aug 23 '16 10:08

ChangeMyName


People also ask

Can pandas write to Excel?

Use pandas to_excel() function to write a DataFrame to an excel sheet with extension . xlsx. By default it writes a single DataFrame to an excel file, you can also write multiple sheets by using an ExcelWriter object with a target file name, and sheet name to write to.


1 Answers

With recent enough pandas use DataFrame.to_excel() with an existing ExcelWriter object and pass sheet names:

from pandas.io.excel import ExcelWriter
import pandas

csv_files = ['my_file1.csv', 'my_file2.csv', ..., 'my_file5.csv']

with ExcelWriter('my_excel.xlsx') as ew:
    for csv_file in csv_files:
        pandas.read_csv(csv_file).to_excel(ew, sheet_name=csv_file)
like image 188
Ilja Everilä Avatar answered Nov 01 '22 17:11

Ilja Everilä