亲宝软件园·资讯

展开

pandas将多个dataframe以多个sheet的形式保存到一个excel文件中

人气:0

要实现这个功能,可能有多种方法,我在这里记录下一个比较方便的方法:

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()

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论