向用户提供Excel(xlsx)文件以便在Django(Python)中下载 [英] Serving Excel(xlsx) file to the user for download in Django(Python)

查看:496
本文介绍了向用户提供Excel(xlsx)文件以便在Django(Python)中下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Django创建和提供excel文件。我有一个jar文件获取参数,并根据参数生成一个excel文件,它没有任何问题。但是当我试图获取生成的文件并将其提供给用户下载时,文件就会被破坏。它有0kb大小。这是我用于生成和生成excel的代码片段。

I'm trying create and serve excel files using Django. I have a jar file which gets parameters and produces an excel file according to parameters and it works with no problem. But when i'm trying to get the produced file and serve it to the user for download the file comes out broken. It has 0kb size. This is the code piece I'm using for excel generation and serving.

def generateExcel(request,id):
    if os.path.exists('./%s_Report.xlsx' % id):
        excel = open("%s_Report.xlsx" % id, "r")
        output = StringIO.StringIO(excel.read())
        out_content = output.getvalue()
        output.close()
        response = HttpResponse(out_content,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = 'attachment; filename=%s_Report.xlsx' % id
        return response
    else:
        args = ['ServerExcel.jar', id]
        result = jarWrapper(*args) # this creates the excel file with no problem
        if result:
            excel = open("%s_Report.xlsx" % id, "r")
            output = StringIO.StringIO(excel.read())
            out_content = output.getvalue()
            output.close()
            response = HttpResponse(out_content,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
            response['Content-Disposition'] = 'attachment; filename=%s_Report.xlsx' % id
            return response
        else:
            return HttpResponse(json.dumps({"no":"excel","no one": "cries"}))

我已经搜索了可能的解决方案,并尝试使用File Wrapper,但结果没有改变。我假设我有将xlsx文件读入StringIO对象的问题。但是没有任何关于如何解决它的想法。

I have searched for possible solutions and tried to use File Wrapper also but the result did not changed. I assume i have problem with reading the xlsx file into StringIO object. But dont have any idea about how to fix it

推荐答案

除了Bruno说的话,你可能需要打开文件二进制模式:

In addition to what Bruno says, you probably need to open the file in binary mode:

excel = open("%s_Report.xlsx" % id, "rb")

这篇关于向用户提供Excel(xlsx)文件以便在Django(Python)中下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆