Odoo_自定义导出excel

1.首先按钮或者菜单触发一个后端方法返回url动作

    def download_xxx_excel(self):
        
        url = '/export_xxx_excel?id={self.id}
        return {
            'type': 'ir.actions.act_url',
            'url': url,
            'target': 'new',
        }

2.controller

from odoo import http
import xlsxwriter, io
import base64

@http.route(['/export_xxx_excel'], type='http', auth="user", website=True)
def export_xxx_excel(self, **kw):
    id = kw.get('id')
    

    output_buffer = io.BytesIO()
    workbook = xlsxwriter.Workbook(output_buffer,
                                options={'default_format_properties': {'font_name': 'Microsoft Yahei', 'font_size': 9, 'valign': 'vcenter'}})
    format_title = workbook.add_format({'font_size': 20, 'align': 'center'})
    format_header = workbook.add_format({'font_size': 10, 'border': True, 'bold': True, 'align': 'center'})
    format_default = workbook.add_format({'text_wrap': True, 'border': True, 'border_color': 'gray'})
    format_left = workbook.add_format({'font_size': 10, 'border': True, 'bold': True, 'align': 'left'})

    worksheet = workbook.add_worksheet("worksheet_name")
    worksheet.write("A1", "Python")
    worksheet.write("B1", "Excel")
    worksheet.write("C1", "xlsx")


    workbook.close()
    output_buffer.seek(0)
    byte_data = output_buffer.getvalue()  # 在内存中读取
    base64_data = base64.b64encode(byte_data)  # 转为base64
    file_name = "xxx.xlsx"
    byte_data = base64.b64decode(base64_data)
    response = http.request.make_response(
        None,
        headers=[
            ('Content-Type', 'application/vnd.ms-excel'),
            ('Content-Disposition', http.content_disposition(file_name))
        ]
    )
    response.stream.write(byte_data)
    return response

 3.需求:Odoo中有一个Binary类型的图片文件,想在生成excel时将该字典的图片添加到excel文件中。

import xlsxwriter, io
import base64
from PIL import Image

    ...

    # Binary类型的字段
    image_data = order_id.company_id.partner_id.signet
    if image_data:
        image = Image.open(io.BytesIO(base64.b64decode(image_data)))
        image_stream = io.BytesIO()
        image.save(image_stream, format='PNG')
        image_stream.seek(0)
    else:
        image_stream = False
    co_worksheet.insert_image('B10:D10', 'image.png', {'image_data': image_stream})

    ...

 

posted @ 2023-08-12 19:25  手可摘星辰。  阅读(321)  评论(0编辑  收藏  举报