Search code examples
odooodoo-8odoo-9odoo-view

How can i generate xls report in odoo


I want to generate my own excel report using Excel report engine in odoo 8. someone please send me a simple excel report sample or any helping URL. I'll be very thankful to you ....


Solution

  • Here is a simple piece of code. There is really a lot of examples on the internet with good explanations. I suggest you go through the code in detail to see how it works (by the way I have copied the code also from somewhere - I cannot remember where. Also have a look at the examples here:https://github.com/OCA/reporting-engine/tree/8.0 The version 8 branch also have a number of examples.

    You can add columns by editing the "my_change" variable.

    from openerp.osv import orm
    from openerp.addons.report_xls.utils import rowcol_to_cell, _render
    from openerp.tools.translate import _
    
    class account_move_line(orm.Model):
        _inherit = 'abc.salesforecast'
    
    # override list in custom module to add/drop columns or change order
        def _report_xls_fields(self, cr, uid, context=None):
        return [
            'contract', 'proposal', 'description', 
            #'amount_currency', 'currency_name',
            ]
    
    # Change/Add Template entries
        def _report_xls_template(self, cr, uid, context=None):   
        """  
        Template updates, e.g. 
    
        my_change = {
            'move':{
                'header': [1, 20, 'text', _('My Move Title')],
                'lines': [1, 0, 'text', _render("line.move_id.name or ''")],
                'totals': [1, 0, 'text', None]},
            }
        return my_change
        """   
        return {}
    

    The code for the parser is as follows.

    import xlwt
    import time
    from datetime import datetime
    from openerp.osv import orm
    
    from openerp.report import report_sxw
    from openerp.addons.report_xls.report_xls import report_xls
    from openerp.addons.report_xls.utils import rowcol_to_cell, _render
    from openerp.tools.translate import translate, _
    from openerp import pooler
    import logging
    _logger = logging.getLogger(__name__)
    
    
    class contract_sales_forecast_xls_parser(report_sxw.rml_parse):
    
        def __init__(self, cr, uid, name, context):
        super(contract_sales_forecast_xls_parser, self).__init__(cr, uid, name, context=context)
        forecast_obj = self.pool.get('msr.salesforecast')
        self.context = context
        wanted_list = forecast_obj._report_xls_fields(cr, uid, context)
        template_changes = forecast_obj._report_xls_template(cr, uid, context)
        self.localcontext.update({
            'datetime': datetime,
            'wanted_list': wanted_list,
            'template_changes': template_changes,
            '_': self._,
        })
    
    def _(self, src):
        lang = self.context.get('lang', 'en_US')
        return translate(self.cr, _ir_translation_name, 'report', lang, src) or src
    
    class contract_sales_forecast_xls(report_xls):
    
    def __init__(self, name, table, rml=False, parser=False, header=True, store=False):
        super(contract_sales_forecast_xls, self).__init__(name, table, rml, parser, header, store)
    
        # Cell Styles
        _xs = self.xls_styles        
        # header
        rh_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
        self.rh_cell_style = xlwt.easyxf(rh_cell_format)
        self.rh_cell_style_center = xlwt.easyxf(rh_cell_format + _xs['center'])
        self.rh_cell_style_right = xlwt.easyxf(rh_cell_format + _xs['right'])
        # lines  
        aml_cell_format = _xs['borders_all']
        self.aml_cell_style = xlwt.easyxf(aml_cell_format)
        self.aml_cell_style_center = xlwt.easyxf(aml_cell_format + _xs['center'])
        self.aml_cell_style_date = xlwt.easyxf(aml_cell_format + _xs['left'], num_format_str = report_xls.date_format)
        self.aml_cell_style_decimal = xlwt.easyxf(aml_cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
        # totals
        rt_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
        self.rt_cell_style = xlwt.easyxf(rt_cell_format)
        self.rt_cell_style_right = xlwt.easyxf(rt_cell_format + _xs['right'])       
        self.rt_cell_style_decimal = xlwt.easyxf(rt_cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
    
        # XLS Template
        self.col_specs_template = {
            'contract':{
                'header': [1, 20, 'text', _render("_('Contract Number')")],
                'lines': [1, 0, 'text', _render("msr_contract_id or ''")],
                'totals': [1, 0, 'text', None]},
            'proposal':{      
                'header': [1, 42, 'text', _render("_('Proposal Number')")],
                'lines': [1, 0, 'text', _render("msr_proposal or ''")],                
                'totals': [1, 0, 'text', None]},
            'description':{      
                'header': [1, 42, 'text', _render("_('Description')")],
                'lines': [1, 0, 'text', _render("name or ''")],                
                'totals': [1, 0, 'text', None]},
        }
    
    def generate_xls_report(self, _p, _xs, data, objects, wb):
    
        wanted_list = _p.wanted_list
        self.col_specs_template.update(_p.template_changes)
        _ = _p._
    
    
    
        #report_name = objects[0]._description or objects[0]._name
        report_name = _("Sales forecast from current contracts")        
        ws = wb.add_sheet(report_name[:31])
        ws.panes_frozen = True
        ws.remove_splits = True
        ws.portrait = 0 # Landscape
        ws.fit_width_to_pages = 1
        row_pos = 0
    
        # set print header/footer
        ws.header_str = self.xls_headers['standard']
        ws.footer_str = self.xls_footers['standard']
    
        # Title
        cell_style = xlwt.easyxf(_xs['xls_title'])
        c_specs = [
            ('report_name', 1, 0, 'text', report_name),
        ]       
        row_data = self.xls_row_template(c_specs, ['report_name'])
        row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style)
        row_pos += 1
    
        # Column headers
        c_specs = map(lambda x: self.render(x, self.col_specs_template, 'header', render_space={'_': _p._}), wanted_list)
        row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
        row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.rh_cell_style, set_column_size=True)        
        ws.set_horz_split_pos(row_pos)   
    
        # account move lines
        for line in objects:
            c_specs = map(lambda x: self.render(x, self.col_specs_template, 'lines'), wanted_list)
            row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
            row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.aml_cell_style)
    
        # Totals           
    
    contract_sales_forecast_xls('report.contract.sales.forecast.xls', 
        'abc.salesforecast',
        parser="contract_sales_forecast_xls_parser")
    

    The xml file will look as follows to setup the necessary actions etc.

    <?xml version="1.0" encoding="utf-8"?>
    <openerp>
      <data>
    
        <record id="action_contract_sales_forecast_xls"     model="ir.actions.report.xml">
          <field name="name">Export Selected Lines To Excel</field>
          <field name="model">abc.salesforecast</field>
          <field name="type">ir.actions.report.xml</field>
          <field name="report_name">contract.sales.forecast.xls</field>
          <field name="report_type">xls</field>
          <field name="auto" eval="False"/>
        </record>
    
        <record model="ir.values" id="contract_sales_forecast_xls_values">
          <field name="name">Export Selected Lines</field>
          <field name="key2">client_action_multi</field>
          <field name="value" eval="'ir.actions.report.xml,' +str(ref('action_contract_sales_forecast_xls'))" />
          <field name="model">abc.salesforecast</field>
        </record>   
    
      </data>
    </openerp>