Enable Dark Mode!
how-to-handle-csv-file-operations-in-odoo-19.jpg
By: Deepika V

How to Handle CSV File Operations in Odoo 19

Technical Odoo 19 Odoo Enterprises Odoo Community

Working with CSV files is an integral part of data management in Odoo 19. This version of Odoo has provided good support for CSV file operations. You can import a number of records into the system or export records to a CSV file to use them outside the system with ease.

The blog aims to provide a detailed overview of working with CSV files in Odoo 19, along with a practical implementation of exporting a custom product.

Odoo 19 comes with a CSV import feature, which allows users to import records into any model without code implementation. The process is simple and requires the following steps:

  1. Open the list view of the model you wish to modify.
  2. Click on the "Import" button, select the CSV file, and map the columns to the Odoo fields.
  3. Validate the data, correct errors, and then proceed with the import, which will be handled by Odoo.

In this blog, we are going to explain how to export the records into a CSV file, i.e., exporting product records into a CSV file. We first create a CSV file inside the Odoo 19 environment. The CSV file is created in write mode, denoted by 'w,' to enter data into it.

With the help of Python’s built-in module ‘csv’, we can create a writer object by calling writer(). The header row is first written into the file by calling writerow(), and then the details of each product record are written into the file line by line.

In some cases, the standard export function may not be enough for your needs, and a custom export solution may need to be implemented to meet the needs of a particular requirement. This provides the developer with more control over the data structure and other export options. The following code snippet provides an example of how a custom export wizard for Odoo 19 can be implemented.

def export_product(self):
   output = io.StringIO()
   writer = csv.writer(output, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
   writer.writerow(['Product Name', 'UOM', 'Price'])
   for product in self.env['product.product'].search([]):
       name = product.product_tmpl_id.name
       uom = product.product_tmpl_id.uom_id.name
       price = product.product_tmpl_id.list_price
       writer.writerow([name, uom, price])
   return output.getvalue().encode('utf-8')

This function exports product data into a CSV file for the Odoo 19 platform.

writer = csv.writer(output, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

This line of code initializes a writer object for the ‘csv’ module.

delimiter=',': indicates that the values in the exported

quotechar='"': Wraps fields in double quotes when necessary.

quoting=csv.QUOTE_MINIMAL: Only wraps values in quotes if required (e.g., if they contain commas or special characters).

writer.writerow([name, uom, price])

The data of the product gets appended as a new row in the CSV. There are several options available for handling quotes. Here are a few options to choose from:

  • csv.QUOTE_ALL: This quotes all the fields, irrespective of their types.
  • csv.QUOTE_MINIMAL: This quotes the fields containing special characters.
  • csv.QUOTE_NONNUMERIC: This quotes all the fields that are not in numeric form.
  • csv.QUOTE_NONE: This does not quote anything.
return output.getvalue().encode('utf-8')
  • The code then retrieves the entire content of the CSV and converts it to UTF-8 bytes, which is necessary to store it in a binary type or to download it.
import io
import csv
import base64
from odoo import models, fields
class ExportCsvWizard(models.TransientModel):
    _name = 'export.csv.wizard'
    _description = 'Export CSV Wizard'
    file = fields.Binary(string='CSV File')
    filename = fields.Char(string='Filename')
    def export_product(self):
        output = io.StringIO()
        writer = csv.writer(output, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        writer.writerow(['Product Name', 'UOM', 'Price'])
        for product in self.env['product.product'].search([]):
            name = product.product_tmpl_id.name
            uom = product.product_tmpl_id.uom_id.name
            price = product.product_tmpl_id.list_price
            writer.writerow([name, uom, price])
        return output.getvalue().encode('utf-8')
    def action_export_csv(self):
        data = self.export_product()
        self.file = base64.b64encode(data)
        self.filename = 'export.csv'
    return {
        'type': 'ir.actions.act_url',
        'url': "/web/content/?model=export.csv.wizard&id=" + str(self.id) +
        "&filename=" + self.filename + "&field=file&download=true",
        'target': 'self'
        }

Finally, the export code writes the CSV content in a format that provides the content to the user in a downloadable format using Odoo 19’s URL-based content delivery feature. Here’s how it works:

  • action_export_csv calls export_product to get the CSV content.
  • It then encodes the data in base64 format and sets the filename to export.csv.
  • It then returns the action URL pointing to the web content delivery route.

So, in summary, export_product() generates the CSV content in a format that gets displayed as a byte-encoded string. This gets displayed to the user in a downloadable format using Odoo 19’s file delivery feature.

  • The encoded data is stored in the file field of the export.csv.wizard model
  • self.filename = 'export.csv', This sets the filename for the exported CSV file as export.csv.

This is the critical section that initiates the download action.

  • The URL is set to /web/content/, which is used for downloading files saved in Odoo 19.
  • The URL includes: model=export.csv.wizard: This is for specifying the model.

It calls using a view :

<record id="export_csv_wizard_form" model="ir.ui.view">
   <field name="name">export.csv.wizard.form</field>
   <field name="model">export.csv.wizard</field>
   <field name="arch" type="xml">
       <form string="Export Products to CSV">
           <footer>
               <button name="action_export_csv"
                       string="Export CSV"
                       type="object"
                       class="btn-primary"/>
               <button string="Cancel"
                       class="btn-secondary"
                       special="cancel"/>
           </footer>
       </form>
   </field>
</record>
  • id=str(self.id): This is for passing the ID of the current record to identify the specific wizard.
  • filename=str(self.filename): This is for specifying the filename to be used for the download.
  • field=file: This is for specifying the binary field that contains the file data.
  • download=true: This indicates that a download is to be made.

The target: 'self', This ensures that the download is made in the same window.

CSV file operations in Odoo 19 provide a robust solution for data management both for the end user and the developers. The built-in import functionality in the system eases the process of entering data in bulk for the end user, while the export functionality provides developers with the flexibility to create a structured output that meets specific needs as required by the business process. As such, the system is capable of handling a wide range of operations involving the use of CSV files in various operational environments.

To read more about How to Handle CSV File Operations in Odoo 18, refer to our blog How to Handle CSV File Operations in Odoo 18.


Frequently Asked Questions

Can I import CSV files with non-standard column names into Odoo 19?

Yes you can. In fact, the import interface provided by Odoo 19 allows you to manually map your column name in the CSV file to the corresponding column name in the model you are trying to import into. This means that even if your column name is "Item Name," you can still map it to "Product Name" during the import before pressing the "Confirm" button.

What happens if there are errors in my CSV file during import into Odoo 19?

It turns out that the Odoo 19 interface provides a validation check before it actually starts to import data into the database. This means that even if there are errors in your CSV file, the Odoo 19 interface will flag them individually and allow you to correct them before importing any data at all. This means you don’t have to worry about incorrect data being imported into your system.

Can I customize the export to include more fields, like Price, UOM, etc., rather than just Name?

Yes, you can definitely customize the export to include more fields, like Price, UOM, etc., rather than just Name, as shown in the export_product() method above. You can definitely include any other fields from the product.product or product.template model instead of just Name by including them in the writer.writerow(). You can even include the product category or reference number, etc., by fetching them inside the loop and including them as additional columns in the header row and data row, respectively.

If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, KINFRA Techno Park
Kakkanchery, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message