如何在Django项目中下载使用python-docx生成的文档?

问题描述 投票:0回答:2

[我试图弄清楚如何在django应用程序中下载由python-docx生成的word文档(我仍在学习,这是我第一次使用文档);借助ajax,我将所有必要的信息发送到视图,并调用使用该信息并返回文档的函数,然后尝试发送此文档作为响应,以便借助“下载”进行下载”按钮(或显示Web浏览器下载对话框)放在我提交数据的同一模板中,但是这里就是我卡住的地方。

发送此文档作为响应,以便在我提交数据的同一模板中使用“下载”按钮(或显示Web浏览器下载对话框)进行下载,但此处是我在此处卡住。

到目前为止,我所拥有的是:

1]在javascript中,我发送的信息如下:

data = {
        categoria: cat,
        familia: fam,
        Gcas: gcas,
        FI: FI,
        FF: FF,
        Test: test,
        Grafica: grafica
    },
        $.ajax({
            type: 'post',
            headers: {
                "X-CSRFToken": csrftoken
            },
            url: url,
            data: { json_data: JSON.stringify(data) },

            success: function (response) {
                $('#instrucciones').hide(); //Hide a div with a message 
                $('#btndesc').show(); //Show the button to download the file generated                
            }
        });
    return false;
}

2)在我的Django视图中:

def Documento(request):
    if request.method == "GET":
        context={}
        context['form'] = catForm
        return render(request, 'report/report_base.html', context)

    if request.method == 'POST':
    #Data from ajax
    datos = request.POST.get('json_data')
    jsondata = json.loads(datos)
    Gcas = jsondata['Gcas']
    FI = jsondata['FI']
    FF = jsondata['FF']
    grafica = jsondata['Grafica']
    #Using function to create the report
    Reporte = ReporteWord(Gcas, FI, FF, grafica)
    #Response
    response = HttpResponse(content_type='application/vnd.openxmlformats-
    officedocument.wordprocessingml.document')
    response['Content-Disposition'] = 'attachment; filename = "Reporte.docx"'
    response['Content-Encoding'] = 'UTF-8'
    Reporte.save(response)
    return response

3)我创建文档的功能如下:

def ReporteWord( gcas, FI, FF, Chart):
    #Cargamos el template
    template = finders.find('otros/Template_reporte.docx')
    document = Document(template) 

    #Header
    logo = finders.find('otros/logo.png')
    header = document.sections[0].header
    paragraph = header.paragraphs[0]
    r = paragraph.add_run()
    r.add_picture(logo)

    #Adding title
    titulo = document.add_heading('', 0)
    titulo.add_run('Mi reporte').bold = True
    titulo.style.font.size=Pt(13)
    .
    Many other steps to add more content    
    .
    .
    #IF I SAVE THE FILE NORMALLY ALL WORKS FINE
    #document.save(r'C:\tests\new_demo.docx')

    return document

我将非常感谢您的任何想法或建议,在此先感谢您。

注意:我没有运气就检查了这些答案(和其他答案)。>>

[Q1Q2Q3Q4

[我试图弄清楚如何在django应用程序中下载由python-docx生成的word文档(我仍在学习,这是我第一次使用文档);在ajax的帮助下,我发送了...

javascript python django httpresponse python-docx
2个回答
0
投票

也许不是执行任务的最优雅的方法,但是在查看了此处的许多帖子,文档等之后,我发现使用wxpython(请参阅下面的链接)对文档进行审核并对现在审核的答案进行了细微改动后发现了一个问题。单击“创建报告”按钮,然后将路径和文件名传递到Django视图,并使用此信息通过以下行保存报告时,显示“另存为”对话框:

"Reporte.save(path)"

0
投票

Python-docx的Document.save()方法接受流而不是文件名。因此,您可以初始化Document.save()对象以将文档保存到其中,然后将其转储给用户。

© www.soinside.com 2019 - 2024. All rights reserved.