pandas将多个dataframe以多个sheet的形式保存到一个excel文件中
作者:互联网
要实现这个功能,可能有多种方法,我在这里记录下一个比较方便的方法:
import
pandas as pd
writer
=
pd.ExcelWriter(
'test.xlsx'
)
data1.to_excel(writer,sheet_name
=
'sheet1'
)
data2.to_excel(writer,sheet_name
=
'sheet2'
)
writer.save()
上面的方法会将原来的excel文件覆盖掉,假如想要对已经存在的excel文件进行修改,可以使用开源工具包(anaconda已附带)openpyxl
import
pandas as pd
from
openpyxl
import
load_workbook
writer
=
pd.ExcelWriter(
'test.xlsx'
,engin
=
'openpyxl'
)
book
=
load_workbook(writer.path)
writer.book
=
book
dataframe.to_excel(excel_writer
=
writer,sheet_name
=
"info5"
)
writer.save()
writer.close()
Dataframe.to_excel多次写入不同Sheet
主要需要pd.ExcelWriter([文件路径])方法
参考官方文档
>>> writer
=
pd.ExcelWriter(
'output.xlsx'
)
>>> df1.to_excel(writer,
'Sheet1'
)
>>> df2.to_excel(writer,
'Sheet2'
)
>>> writer.save()
以下为实际应用:
"""
df1,df2均为sql查询来的数据
excel_filepath为要生成保存的excel文件地址
"""
write
=
pd.ExcelWriter(excel_filepath)
df1
=
pd.Dataframe(d_f1)
excel_header
=
[
'日期'
,
'年龄'
]
#excel的标题
df1.to_excel(write,sheet_name
=
'Sheet1'
,header
=
excel_header,index
=
False
)
df2
=
pd.Dataframe(d_f2)
excel_header
=
[
'日期'
,
'人数'
]
df2.to_excel(write,sheet_name
=
'Sheet2'
,header
=
excel_header,index
=
False
)
write.save()
以上就是本文的全部内容,希望对大家的学习有所帮助
标签:sheet,多个,writer,excel,header,pd,ExcelWriter 来源: https://www.cnblogs.com/shclbear/p/16698134.html