如何使用 Python Pandas 将 CSV 文件写入 XLSX?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39099008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:52:33  来源:igfitidea点击:

How to write CSV files into XLSX using Python Pandas?

pythonexcelpandascsvxlsx

提问by ChangeMyName

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

我有几个 .csv 文件,我想将它们作为电子表格写入一个 .xlsx 文件。

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

我已使用以下代码将这些 .csv 文件加载到 Pandas.DataFrame 中:

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.

但是我在 Pandas 中找不到任何可以将这些 DataFrame 作为单独的电子表格写入一个 .xlsx 文件的函数。

Can anyone help me with this?

谁能帮我这个?

回答by Ilja Everil?

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

最近有足够多的Pandas使用DataFrame.to_excel()现有ExcelWriter对象并传递工作表名称:

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)