2016-10-02 87 views
0

我正在使用Google App Engine和python 2.7。並且需要生成內存中的xls文件並將其發送給用戶進行下載。發送excel文件以下載GAE python

我在網上發現了很多主題,但其中任何一個都無法幫到我。 我試圖使用的相關主題:1)this is with Blobs, I tried at first,2)without Blob,3)with force-download MIME type,我也嘗試過使用googlecloudstorage(找不到主題鏈接)。

這裏是我的代碼:

import StringIO 

class ExcelHandler(BaseHandler): 

def post(self): 

    """Save members to excel document and send to user""" 

    sheet = pyexcel.Sheet([[1, 2], [3, 4]]) 
    filesheet = StringIO.StringIO() 
    sheet.save_to_memory('xls', filesheet) 
    filesheet.close() 

    self.response.write(sheet) 
    self.response.headers['Content-Type'] = 'application/force-download' 
    self.response.headers['Content-Transfer-Encoding'] = 'utf-8' 
    self.response.headers['Content-Disposition'] = 'attachment; filename=test.xlsx' 

的問題是在發送響應(而不是在創建文件)。我嘗試了不同的'Content-Type': 'application/vnd.ms-excel', 'application/download', 'application/force-download', 'application/octet-stream', 'application/vnd .openxmlformats - officedocument.spreadsheetml.sheet」

但我已經達到了最好的迴應是在圖片:

我不能執行我的瀏覽器開始從服務器下載數據。我想我的請求中可能有些東西應該對服務器說'嗨,我想下載',但這只是我的想法,我沒有發現任何關於這個的東西。將感謝任何幫助!

這裏也是我的要求:

POST /reg/excel HTTP/1.1 
Host: 0.0.0.0:8080 
Connection: keep-alive 
Content-Length: 0 
Accept: */* 
Origin: http://0.0.0.0:8080 
X-Requested-With: XMLHttpRequest 
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 
Referer: http://0.0.0.0:8080/competition?dbKey=agpkZXZ- dG1tb3NjchgLEgtDb21wZXRpdGlvbhiAgICAgICgCww 
Accept-Encoding: gzip, deflate 
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4 

和應對調試器:

HTTP/1.1 200 OK 
content-disposition: attachment; filename=test.xlsx 
content-transfer-encoding: utf-8 
cache-control: no-cache 
content-type: application/force-download 
Content-Length: 64 
Server: Development/2.0 
Date: Sun, 02 Oct 2016 15:36:20 GMT 

編輯1:(嘗試通過voscausa答案)

Response changed its format. I am going to try to write another data structure (not Sheet) to response

回答

1

嘗試這個:

output = StringIO.StringIO() 
.......   

self.response.headers[b'Content-Type'] = b'application/vnd.ms-excel; charset=utf-8' 
self.response.headers[b'Content-Disposition'] = b'attachment; filename=test.xlsx' 
self.response.write(output.getvalue()) 
+0

'Content-Type'是這裏的關鍵。 –

+0

@voscause,我試了你的答案,並得到不同的迴應(看編輯1)。猜測這可能是我在save_to_memory方法中的錯誤。我要檢查我應該寫什麼來回應(表/書/等),並添加評論,如果它會幫助。 –