This question has been flagged
2 Replies
22443 Views

Hello,

I want to generate excel report on button click, can any one help me out how this can be done.

Avatar
Discard
Best Answer

Hello,


on the button call the method. and into the method write your code to generate the excel report.

here i am write some code from where you can get some basic idea.

import xlwt
from xlsxwriter.workbook import Workbook
from cStringIO import StringIO
import base64
class your_object(models.Model):
    _name = 'your.object.'
    @api.multi
    def generate_excel_report(self):
        filename= 'filename.xls'
        workbook= xlwt.Workbook(encoding="UTF-8")
        worksheet= workbook.add_sheet('Sheet 1')
        style = xlwt.easyxf('font: bold True, name Arial;)
        worksheet.write_merge(0,1,0,3,'your data that you want to show into excelsheet',style)
        fp = StringIO()
        workbook.save(fp)
        record_id = self.env['wizard.excel.report'].create({'excel_file': base64.encodestring(fp.getvalue()),
                                                                                                'file_name': filename},)
        fp.close()
        return {'view_mode': 'form',
                    'res_id': record_id,
                    'res_model': 'wizard.excel.report',
                    'view_type': 'form',
                    'type': 'ir.actions.act_window',
                    'context': context,
                  'target': 'new',
       }

class wizard_excel_report(models.Model):
    _name= "wizard.excel.report"
    excel_file = fields.Binary('excel file')
    file_name = fields.Char('Excel File', size=64)


make the form view(xml code) of "wizard_excel_report" object as per your needs

Avatar
Discard
Author

thanks

Best Answer

You'll need to write a python method in your model that generates an excel, saves it to a stream and save it to a binary field.

In the view you can call this method to with a button.

With python 2.7 for odoo 10:

import xlwt
import base64
import StringIO

@api.multi
def generate_excel(self):
    stream = StringIO.StringIO()
    book = xlwt.Workbook(encoding='utf-8')
    sheet = book.add_sheet(u'Sheet1')
    sheet.write(row, col, data)
    book.save(stream)
    self.your_binary_field = base64.encodestring(stream.getvalue())
    self.your_file_name = self.name

In the view you then have a button that calls that method

<field name="file_name" invisible="1"/>
<field name="document" filename="file_name"/>
<button name="generate_excel" type="object" string="Generate excel"/>

You'll need to adjust it for python3 and odoo 11 views. Hope it helps. 

Avatar
Discard
Author

thank you!

no problem, had to figure how to do this just this week so glad to help.