odoo自定义导出excel

1.odoo导出需借助TransientModel模型,即wizard的视图;先创建模型:

class WizardSaleOrderExcelReport(models.TransientModel):
    _name = 'wizard.sale.order.excel.report'

    name = fields.Char('File Name', size=64)
    file_name = fields.Char('download file name', size=64)
    report = fields.Binary('Prepared File', filters='.xls', readonly=True)

2.创建导出按钮(所写为导航栏的按钮,并未添加到通用的动作当中)及wizard form视图:



    
        sale_order_xlsx
        sale.order
        
        
            
                

其中:file_name为所需下载文件的名称。

3.使用python的xlwt生成excel,使用sudo pip intall xlwt安装依赖包;代码如下:

# _*_ coding: utf-8 _*_
import xlwt
import StringIO
import base64

class SaleOrder(models.Model):
    _inherit = "sale.order"

    @api.multi
    def generated_excel_report(self, record):

        workbook = xlwt.Workbook()
        # Style for Excel Report
        styletitle = xlwt.easyxf(
            'font:bold True, color Orange, height 400;  borders: top double; align: horiz center; pattern: pattern solid, fore_colour gray25;',
            num_format_str='#,##0.00')
        
        sheet = workbook.add_sheet("Sale Order")

        sheet.write_merge(0, 0, 0, 3, 'Sale Order')
        fr = sheet.row(0)
        fr.set_style(st)
        sheet.write_merge(1, 1, 0, 1, 'Base Information')
        sheet.write_merge(1, 1, 2, 3, 'Data')

        sheet.write(2, 0, 'Sequence', styletitle)
        sheet.write(2, 1, 'Name', styletitle)
        sheet.write(2, 2, 'Explain', styletitle)
        sheet.write(2, 3, 'quantity', styletitle)

        sheet.col(0).width = 700 * (len('Name') + 1)
        sheet.col(1).width = 700 * (len('Working Address') + 1)
        sheet.col(2).width = 700 * (len('Working Mobile') + 1)
        sheet.col(3).width = 700 * (len('Working Mobile') + 1)
        
        row = 3
        for index, rec in enumerate(self.order_line):
            sheet.write(row, 0, str(int(index + 1)), style0)
            sheet.write(row, 1, rec.product_id.name, style0)
            sheet.write(row, 2, rec.name, style0)
            sheet.write(row, 3, rec.product_uom_qty, style0)
           
            row += 1
        workbook.save('/tmp/sale_order.xls')
        result_file = open('/tmp/sale_order.xls', 'rb').read()

        attachment_id = self.env['wizard.sale.order.excel.report'].create({
            'name': 'Sale Order.xls',
            'file_name': 'Sale Order.xls',
            'report': base64.encodestring(result_file)
        })

        return {
            'name': _('Notification'),
            'context': self.env.context,
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'wizard.sale.order.excel.report',
            'res_id': attachment_id.id,
            'data': None,
            'type': 'ir.actions.act_window',
            'target': 'new'
        }

 

你可能感兴趣的:(Odoo)