下载使用python-docx创建的文档

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

我正在尝试在Odoo中导出word报告,我正在使用python-docx库,

码:

document = Document()            

records = result

table = document.add_table(rows=0, cols=4,style='Table Grid')  
for att  in records:
    row_cells = table.add_row().cells
    cnt = 0  
    for attdet  in att:
        #row_cells[0].style('text-align: center;vertical-align: middle;') 
        if (cnt == 0):
            row_cells[0].add_paragraph(attdet.serial_no, 'List Bullet')#[0].text = attdet.serial_nobold
            row_cells[1].add_paragraph(attdet.name, 'List Bullet')#[1].text = attdet.name
        else:
            row_cells[2].add_paragraph(attdet.serial_no, 'List Bullet')#.text = attdet.serial_no
            row_cells[3].add_paragraph(attdet.name, 'List Bullet')#.text = attdet.name
        cnt = cnt+1

document.add_page_break()

pdfhttpheaders = [('Content-Type','application/msword')]
return request.make_response(document, headers=pdfhttpheaders)

而不是将文档保存到文件夹中,我需要在按钮单击时下载此word文档,

我收到以下错误,

AttributeError: 'JsonRequest' object has no attribute 'make_response'

请任何人指导我解决此错误。

odoo-10 python-docx
2个回答
1
投票

从我的角度来看,您必须改变生产方式,并专门获取文档的生成和访问位置。

更简单的方法我认为将使用按钮返回一个动作url dict,将请求重定向到控制器,并在查询字符串中使用正确的数据,以便能够生成文档作为响应,你这样做的方式。就像是:

return {
    'type': 'ir.actions.act_url',
    'url': '/report/docx/content/custom',
    'target': 'self',
}

然后,您可以将生成docx报告的代码放入方法控制器中,如下所示:

from odoo import http, tools, _
from odoo.http import request, Controller

class CustomController(Controller):

    @http.route(['/report/docx/content/custom'], type='http', auth="public")
    def report_docx(self, **kwargs):
        # your code of report generation that use request.make_response

只需使用URL查询字符串(如记录ID)或控制器中可能需要的任何其他数据将足够的信息传递给控制器​​,但通常记录ID就足够了


0
投票

好吧,我怀疑这里的错误比这更多,但你需要先保存文档,也许是这样的io.BytesIO流:

import io

# ...

docx_stream = io.BytesIO()
document.save(docx_stream)
docx_bytes = docx_stream.getvalue()

docx_bytes值是生成的.docx文件的实际内容,这是您在响应中所需的内容。 document值只是表示文档的内存中对象图,并且与.docx文件没有直接对应关系(除了它可以使用其.save()方法创建一个.docx文件。

我怀疑响应需要是多部分的,但也许有更多了解Odoo的人可以帮助你完成这一部分。

另外,我认为内容类型需要是application/vnd.openxmlformats-officedocument.wordprocessingml.document才能正常工作。你拥有的那个('application / msword')是旧的.doc格式(Word 2003和之前的版本)。

我不确定pdfhttpheaders这个名字的用途是什么。这与PDF格式无关。我希望http_headers对于那个标识符来说是更明智的选择。

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