简体   繁体   中英

Send excel file for downloading GAE python

I am using Google App Engine with python 2.7. And there is need to generate in-memory xls-file and send it to user for downloading.

I found amount of topics in web, but any of them can't help me. Related topics that I've tried to use: 1) this is with Blobs, I tried at first , 2) without Blob , 3) with force-download MIME type , also I've tried to use googlecloudstorage (can't find links to topics).

Here is my code:

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'

The problem is in sending response (not in creating file). I tried different 'Content-Type': 'application/vnd.ms-excel', 'application/download', 'application/force-download', 'application/octet-stream', 'application/vnd.openxmlformats - officedocument.spreadsheetml.sheet'

But the best response I've achieved is as on picture:

I can't enforce my browser to start downloading data from server. I guess there may be something in my Request that should say to server 'Hey, I want to download', but it is only my thoughts, I've not found anything about that. Will appreciate any help!

Here is also my Request:

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

and Response at debugger:

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

EDIT 1: (try answer by voscausa)

响应更改了其格式。我将尝试编写另一个数据结构(而非工作表)以进行响应

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM