This table converts to a CSV file:
‘Programming Languages’,‘File Extensions;
‘Java’,’.java’
‘C’,’.c’
‘Python’,’.py’
In Odoo we can use a python package to handle the CSV file operations called ‘CSV’. This ‘CSV’ package is quite simple to understand the functionalities and operations. Let us see the read and write operations of the CSV file within the Odoo environment.
First Import package to the python file:
import csv
Let's see how to write data from a record. Here we taking an example of products.
The first step we create a new file. In our example, product.csv is the file name. For writing a file we use the mode ‘w’.
with open('product.csv', mode='w') as file:
Next, we have to write data into the file. Using writer function we can write data to the file. For each row, we will use loop and will go through each record. To write each row call writerrow() function.
writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
# create a row contains heading of each column
writer.writerow(
[‘Product Name’, ‘UOM’, ‘Price’, ‘Amount’])
# fetch products and write respective data.
for product in self.env[‘product.product’]:
name = product.product_tmpl_id.name
uom = product.product_tmpl_id.uom_id.name
price = product.product_tmpl_id.list_price
amount = product.product_tmpl_id.taxes_id.amount
writer.writerow(
[name, uom, price, amount,]
delimiter: This parameter’s value is used to separate the columns.
quotechar: This is used to set the value of the field enclosed with like ‘ or “
quoting: This parameter has the following values,
csv.QUOTE_ALL - Quote everything, regardless of type.
csv.QUOTE_MINIMAL - fields are quote with special characters.
csv.QUOTE_NONNUMERIC - Only non-numerical values will quote.
csv.QUOTE_NONE – fields are not quoted whether it is numerical or not.
In this example first, we use the writer function to write the header part into the file. Then we looped through the records and taken the only necessary fields from the records.
If you want to read the file using the following code:
with open('product.csv', 'r', encoding="utf-8") as f2:
# file encode and store in a variable ‘data’
data = str.encode(f2.read(), 'utf-8')
Next, we need to get the file. So we return this data into a wizard.
class ExportProductWizard(models.TransientModel):
_name = 'wiazrd.product.csv'
csv_product = fields.Binary()
name_file = fields.Char()
# function will trigger from the export button in customer export
def export_customers(self):
# call the function generate csv files
file = self.env['product.csv'].export_product()
self.csv_product = base64.encodestring(file)
self.name_file = ‘product.csv'
return {
'type': 'ir.actions.act_url',
'url': "web/content/?model=wizard.product.csv&id=" + str(self.id) +
"&filename=product.csv&field=csv_product&download=true&name_file=" + self.name_file,
'target': 'self',
}