Odoo13中下载Excel文件如何自定义文件名?
Odoo13 自定义Excel下载文件名解决方案
方法1:直接触发文件下载(推荐)
不需要创建临时记录,直接在action_download方法中返回文件下载响应,可直接指定目标文件名:
import base64 from io import BytesIO import xlwt import odoo.http as http class MailingContact(models.Model): _inherit = 'mailing.contact' def action_download(self): filename = "template.xlsx" workbook = xlwt.Workbook(encoding='utf-8') sheet1 = workbook.add_sheet('saff', cell_overwrite_ok=True) format1 = xlwt.Style.easyxf('font: color black, bold True;') sheet1.col(0).width = 7000 sheet1.write(0,0,"column 1", format1) stream = BytesIO() workbook.save(stream) stream.seek(0) # 将文件指针移到开头 return http.send_file( stream, filename=filename, as_attachment=True, mimetype='application/vnd.ms-excel' # xlwt生成的是xls格式,对应此MIME类型 )
注意:xlwt库生成的是
.xls格式文件,若需要.xlsx格式,建议改用openpyxl库。
方法2:保留临时记录表单,指定下载文件名
如果需要通过表单界面展示并下载,需修改模型字段属性并配置视图:
- 修改
custom.excel模型的Binary字段,添加filename关联:
class CustomExcel(models.TransientModel): _name = 'custom.excel' _rec_name = 'datas_fname' file_name = fields.Binary(string="Report", readonly=True, filename='datas_fname') datas_fname = fields.Char(string="Filename")
- 为
custom.excel添加form视图(在模块的XML文件中定义):
<odoo> <record id="view_custom_excel_form" model="ir.ui.view"> <field name="name">custom.excel.form</field> <field name="model">custom.excel</field> <field name="arch" type="xml"> <form string="Download Template"> <group> <field name="file_name" readonly="1"/> </group> <footer> <button string="Close" class="btn-secondary" special="cancel"/> </footer> </form> </field> </record> </odoo>
- 修改
action_download方法的返回值,指定视图ID:
def action_download(self): filename = "template.xlsx" workbook = xlwt.Workbook(encoding='utf-8') sheet1 = workbook.add_sheet('saff', cell_overwrite_ok=True) format1 = xlwt.Style.easyxf('font: color black, bold True;') sheet1.col(0).width = 7000 sheet1.write(0,0,"column 1", format1) stream = BytesIO() workbook.save(stream) out = base64.encodebytes(stream.getvalue()) excel_id = self.env['custom.excel'].create({ "datas_fname": filename, "file_name": out }) return { 'res_id': excel_id.id, 'name': 'Template Download', 'view_mode': 'form', 'res_model': 'custom.excel', 'view_id': self.env.ref('your_module_name.view_custom_excel_form').id, 'type': 'ir.actions.act_window', 'target': 'new' # 以弹窗形式打开表单 }
替换
your_module_name为你实际的模块名称。
内容的提问来源于stack exchange,提问作者perl
相关产品推荐
相关产品推荐

