Pandas輸出Excel文件流


一、前言

業務有個需求,篩選后的結果導出excel,起初實現方案:先在本地生成一個臨時excel文件,然后返回,感覺麻煩,隨利用pandas生成一個Excel文件流,直接Response,不用考慮臨時文件寫/刪問題。

二、實現

官網文檔地址:https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#writing-excel-files-to-memory

from io import BytesIO

bio = BytesIO()

# By setting the 'engine' in the ExcelWriter constructor.
writer = pd.ExcelWriter(bio, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')

# Save the workbook
writer.save()

# Seek to the beginning and read to copy the workbook to a variable in memory
bio.seek(0)
workbook = bio.read()

 

三、示例

In [1]:  import pandas as pd                                                                                     

In [2]: order_info_dict = dict()                                                                                 

In [3]: order_info_dict["下單用戶"] = ["hello", "world", "hha", "hehe", "xixi"]                                  

In [4]: order_info_dict["訂單號"] = [1,2,3,4,5]                                                                  

In [5]: df = pd.DataFrame(order_info_dict)                                                                       

In [6]: from io import BytesIO                                                                                   

In [7]: bio = BytesIO()                                                                                          

In [8]: writer = pd.ExcelWriter(bio, engine='xlsxwriter')                                                        

In [9]: df.to_excel(writer, sheet_name='Sheet1', index=None)                                                                 

In [10]: writer.save()                                                                                           

In [11]: bio.seek(0)                                                                                             
Out[11]: 0

In [12]: workbook = bio.read()                                                                                   

In [13]: with open("1.xlsx", wb) as f:     # 此處代碼只是演示,可以以字節形式寫入文件。
    ...:     f.write(worbook) 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM