1. 程式人生 > 實用技巧 >BZOJ-2795 [Poi2012]A Horrible Poem(hash+線性篩)

BZOJ-2795 [Poi2012]A Horrible Poem(hash+線性篩)

要實現這個功能,可能有多種方法,我在這裡記錄下一個比較方便的方法:

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援碼農教程。