发送excel文件以下载GAE python

时间:2016-10-02 16:05:22

标签: python excel google-app-engine

我正在使用带有python 2.7的Google App Engine。并且需要生成内存中的xls文件并将其发送给用户进行下载。

我在网上找到了大量的主题,但其中任何一个都无法帮助我。 我尝试使用的相关主题: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': '应用程序/ vnd.ms-Excel的, “应用程序/下载”, “应用程序/力下载”, “应用程序/八位字节流”, '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 个答案:

答案 0 :(得分: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())