pandas,pd.ExcelWriter保存結果到已存在的excel文件中

背景:pandas支持將DataFrame數據直接保存到excel中
 
保存的case以下:
import pandas as pd
with pd.ExcelWriter('a.xls') as writer:
    df1.to_excel(writer, 'sheet1')
    df2.to_excel(writer, 'sheet2')
 
結果:新生成的結果sheet1和sheet2生成後,會將原有的excel表格中的數據所有覆蓋
 
因此,在已有的excel文件上操做的方法以下
from openpyxl import load_workbook
book = load_workbook('a.xlsx')
writer = pd.ExcelWriter('a.xlsx', engine='openpyxl')
writer.book = book
df1.to_excel(writer, 'sheet1')
df2.to_excel(writer, 'sheet2')
writer.save()
 
備註:
一、openpyxl爲第三方包,安裝方法:
pip3 install openpyxl

 

 
二、df1和df2爲DataFrame格式數據,相似
df1 = pd.DataFrame({"需求名稱": prd_name, "需求bug總數": prd_bugnum, "Android BUG數": prd_bugnum_android,
                    "iOS BUG數": prd_bugnum_ios, "server BUG數": prd_bugnum_server, "FE BUG數": prd_bugnum_fe,
                    "需求變動個數": prd_bugnum_pm, "設計缺陷個數": prd_bugnum_design
                    })
相關文章
相關標籤/搜索