pandas 輸出 excel 文件流 StringIO or BytesIO

# Writing Excel files to memory

# Pandas supports writing Excel files to buffer-like objects such as StringIO or BytesIO using ExcelWriter.

# Safe import for either Python 2.x or 3.x
try:
    from io import BytesIO
except ImportError:
    from cStringIO import StringIO as BytesIO

bio = BytesIO()

# By setting the 'engine' in the ExcelWriter constructor.
writer = pd.ExcelWriter(bio, engine='xlsxwriter')
# 這裏df就是你數據的pandas.DataFrame的數據
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()

"""engine is optional but recommended. Setting the engine determines the version of
 workbook produced. Setting engine='xlrd' will produce an Excel 2003-format workbook
  (xls). Using either 'openpyxl' or 'xlsxwriter' will produce an Excel 2007-format
   workbook (xlsx). If omitted, an Excel 2007-formatted workbook is produced. """

上面摘自:pandas官方文檔-writing-excel-files-to-memory

根據官方文檔就可以直接得到一個文件流在內存中,然後只需要返回Response就好了。
我這裏使用的是Django rest framework 框架。

非常坑的一點是,我之前一直使用的rest_framework.response.Response,直接將文件流傳過去會一直報錯,提示utf-8編碼的問題,但是其實並不是編碼的問題,而是Response接收的是data參數,而我們返回的是二進制的數據。所以,我們應該使用django.http.HttpResponse這個,他接收的是content,一個二進制的bytestring。
所以HttpResponse(workbook, content_type=content_type)這樣就可以了。

然後就是設置content-type,這樣瀏覽器就知道我們是以什麼形式給他的。
我們office excel 2007的content-type是application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
具體可以參考 HTTP content-type 對照表 , 當然沒有的話可以自己搜索。

還有一點就是Content-Disposition參數:
attachment — 作爲附件下載
inline — 在線打開
具體使用如:
response['Content-Disposition'] = 'attachment;filename=文件名.txt'
response['Content-Disposition'] = 'inline;filename=文件名.txt'
這裏還有一個坑就是如果你把文件名當做參數傳進去,使用 % 或者 format 來格式化。一旦這個文件名中間包括空格,在http響應的時候就是Content-Disposition:attachment;filename=i love you.txt 然後系統會自動將這個空格將後面的捨棄掉。這樣你再拿到這個文件的時候就只有第一個空格之前的filename,沒有後綴名,都無法直接打開。
可以的辦法就是使用轉義符,使用雙引號Content-Disposition:attachment;filename=\"i love you.txt\",這樣你就可以將文件名使用格式化放進去了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章