In the present-day usage of the software in business, reports play a vital part in data analysis and management. There are several methods of report creation in Odoo including PDF,  XLSX, and CSV according to different requirements of the business. CSV or Comma Separated Values is considered to be one of the frequently used methods of creating data exporting documents in Odoo. CSV file format is convenient and simple, as well as compatible with many programs including Microsoft Excel, Google Sheets, and LibreOffice Calc.

 

In the Odoo version 18, it is possible to create CSV reports in Python together with HTTP Controllers, which is useful if the user needs a simple format of exportation for their massive data such as:

 

                                                                                                                                                                                                                                                   

 

How it works


In order to make the process of generating CSV report possible in Odoo, the workflow contains several steps such as the creation of a button on the Sales Orders' interface and writing some code in the backend, which will generate and allow downloading the file. For making the above-mentioned process possible, the following elements should be utilized:

1. Report actions through python models


2. XML views for creating custom buttons


3. Javascript code for triggering custom actions (depends on the chosen implementation)


4. HTTP controllers for generation and download of a CSV report


5. CSV files processed by means of the standard csv library available in Python


In this way, the business data in Odoo may be exported in the lightweight Excel-friendly  CSV format.

1. Python Model Implementation (sale_order.py)


First, we'll create the Python model that handles the report generation logic. This file defines the core functionality for creating our CSV reports.

 

# -*- coding: utf-8 -*-
import io
import json
from odoo import models
from odoo.tools import date_utils
import csv
class SalesOrder(models.Model):
 _inherit = "sale.order"
 def action_sale_csv_report(self):
 data = {
 'name': self.name,
 'customer': self.partner_id.name,
 }
 return {
 'type': 'ir.actions.report',
 'data': {
 'model': 'sale.order',
 'options': json.dumps(data,
 default=date_utils.json_default),
 'output_format': 'csv',
 'report_name': 'CSV Report',
 },
 'report_type': 'csv',
 }
 def get_csv_report(self, data, response):
 output = io.StringIO()
 writer = csv.writer(output, delimiter=',', quoting=csv.QUOTE_ALL, lineterminator='\n')
 writer.writerow(['name', 'Customer'])
 writer.writerow([
 data.get('name', ''),
 data.get('customer', ''),
 ])
 response.stream.write(output.getvalue().encode('utf-8-sig'))
 output.close()


2. Adding A CSV Report Button in the `sale_order_views.xml` File

This file has the CSV Report button.


It is, in the form that people use to view the Sale Order. When you click on the CSV Report button it makes the Python method run. That method generates the CSV report for the Sale Order. The CSV Report button is really important, for the Sale Order.

 

<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
 <record id="sale_view_inheritted_id" model="ir.ui.view">
 <field name="name">sale.order.form.inherit.sale</field>
 <field name="model">sale.order</field>
 <field name="inherit_id" ref="sale.view_order_form"/>
 <field name="arch" type="xml">
 <xpath expr="//button[@name='action_confirm']" position="after">
 <button name="action_sale_csv_report" string="CSV Report" type="object" class="btnprimary"/>
 </xpath>
 </field>
 </record>
</odoo>


3. Javascript Action Manager


The Javascript handler manages the report generation action and handles the download


/** @odoo-module **/
import {registry} from "@web/core/registry";
import {BlockUI} from "@web/core/ui/block_ui";
import {download} from "@web/core/network/download";
/**
This handler is responsible for generating CSV reports.
*/
registry.category("ir.actions.report handlers").add("csv", async function (action) {
 if (action.report_type === 'csv') {
 BlockUI;
 await download({
 url: '/csv_reports',
 data: action.data,
 complete: () => unblockUI,
 error: (error) => self.call('crash_manager', 'rpc_error', error),
 });
 return true
 }
});


4. Controller Implementation (main.py)


Now we need to make the controller. The controller is in charge of creating the CSV report  and letting people download it. The controller gets a request for a CSV report from the end it takes the data it gets from the Python model and then it makes the CSV report. The controller does a things: it gets the request for the CSV report it processes the data, from the Python model and then it creates the CSV report. The CSV report is what the controller is making.. This controller also ensures that the necessary headers are set for the downloading of the report in the CSV format. Upon completion of this process, the CSV report gets downloaded automatically on the system of the user.

 

# -*- coding: utf-8 -*-
import json
from odoo import http
from odoo.http import content_disposition, request
from odoo.http import serialize_exception as _serialize_exception
from odoo.tools import html_escape
class CSVReportController(http.Controller):
 """CsvReport generating controller"""
 @http.route('/csv_reports', type='http', auth='user', methods=['POST'], csrf=False)
 def get_report_csv(self, model, options, output_format, **kw):
 """
 Generate an CSV report based on the provided data and return it as a
 response.
 """
 uid = request.session.uid
 report_obj = request.env[model].with_user(uid)
 options = json.loads(options)
 token = 'dummy-because-api-expects-one'
 try:
 if output_format == 'csv':
 response = request.make_response(
 None,
 headers=[
 ('Content-Type', 'text/csv'),
 ('Content-Disposition',
 content_disposition('Sale Report' + '.csv'))
 ]
 )
 report_obj.get_csv_report(options, response)
 response.set_cookie('fileToken', token)
 return response
 except Exception as e:
 se = _serialize_exception(e)
 error = {
 'code': 200,
 'message': 'Odoo Server Error',
 'data': se
 }
 return request.make_response(html_escape(json.dumps(error)))


when we click the “CSV Report” button the get_report_csv() function will trigger

 

                                                                                                                                                                                       

 

 


The download link for the CSV report created will be based on the implementation process through the form view on the Sale Order. The screenshot provided below shows that the report export will occur in the CSV format.

 

 

                                                                                                                                                                                           

 

 

In this manner, it is possible to efficiently create and download a custom CSV report right from the Sale Order form view in Odoo. Using such methods as defining Python models, creating XML views, setting up JavaScript functions, and configuring HTTP controllers, it is now possible to implement a flexible solution for exporting company data using CSV formats in Odoo. As CSV formats work well with programs like Microsoft Excel, Google Sheets and LibreOffice Calc this approach will be really helpful for doing things with the exported data.You can easily use the exported data in these programs.

 

They are all very common so it makes sense to use CSV.It is a choice, for further operations.The data can be easily. Edited in Microsoft Excel, Google Sheets or LibreOffice Calc.

Leave a comment

Book a Free Consultation

From our ready‑to‑use products and services to tailor‑made softwares, we help you make the right tech move for your organization. Fill in your details below, and our experts will reach out to schedule your free consutlation session and explore what fits your needs best.

Book a Free Demo

From our ready‑to‑use products and services to tailor‑made softwares, we help you make the right tech move for your organization. Fill in your details below, and our experts will reach out to schedule your free consutlation session and explore what fits your needs best.

Successfully Subscribed!