Decoding problems when returning xlsxwriter response with pyramid

时间:2015-09-14 16:00:54

标签: python pyramid xlsxwriter

I though this question would solve my problem, and I followed the Simple HTTP Server example but I'm getting different issues that I can't find a solution for.

I want to generate an Excel file in my server and return it to the user with an Http response. I'm using xlsxwriter to build the file and a pyramid framwork in my server. I've managed to build the file and return it, but then first issue is LibreCalc (I'm testing on Ubuntu 14) asks me how I want to import the file. It doesn't matter what I select I get this error message

General Error. General input/output error.

If I just build and save the file without returning it as a response, it opens fine.

My code to build the file:

output = StringIO()  
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.add_worksheet()

# add the data

workbook.close()

excelcontent = output.getvalue()
response = Response(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                    body=excelcontent)
response.headers.add('Content-Disposition',
                     "attachment; filename=%s.xlsx" % nice_filename)
response.headers.add('Access-Control-Expose-Headers','Content-Disposition')
response.headers.add("Content-Length", str(len(excelcontent)))
response.headers.add('Last-Modified', last_modified)
response.headers.add("Cache-Control", "no-store")
response.headers.add("Pragma", "no-cache")

return response

And I handle the response:

    $http({
        method: 'POST',
        url: url,
        data: data},
        {responseType: 'arraybuffer'}
    ).success(function (response, status, headers, config) {
        var file = new Blob([response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        var fileURL = URL.createObjectURL(file);
        var result = document.getElementsByClassName("excel_hidden_download");
        var anchor = angular.element(result);
        var filename_header = headers('Content-Disposition');
        var filename = filename_header.split('filename=')[1];
        anchor.attr({
            href: fileURL,
            target: '_blank',
            download: filename
        })[0].click();
    })

I thought at first it could have something to do with the fact that I use UTF-8 encoding in the python file, but since I can build and open the file otherwise, I don't think it does.

# -*- coding: utf-8 -*-

1 个答案:

答案 0 :(得分:1)

我能够按照this问题的答案找到解决方案。我不确定究竟是什么诀窍,但这是我的结果代码:

myScope

它完美无缺,我只需要更改http代码。顺便说一下,我使用angular-file-saver作为saveAs函数。