We can rewrite this table into the CSV format as below:
‘File Format’,‘Extension
‘CSV’,’.csv’
‘XML’,’.xml’
‘Python’,’.py’
Here we are going to use the python ‘CSV’ package to perform CSV file operations. It is very easy to handle write and read operations. Let’s see how to use CSV in odoo. Here I’m using Odoo 12. And it’s based on Python 3. So not much changes in Odoo 13.
Import package:
import csv
Let's see how to write record data into a CSV file.
Consider an example of we are exporting records of products.
First, we need to create a CSV file. In the following example, export.csv is the file name. While writing a file mode must be ‘w’.
with open('export.csv', mode='w') as file:
Then we have to use the writer function for writing data into this file and iterate the records over the lines, for that we can use the writer row() 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: which defines the separator.
quotechar: which defines the data enclosed with.
quoting: it has some values,
csv.QUOTE_ALL - Quote everything, regardless of type.
csv.QUOTE_MINIMAL - Quote fields with special characters.
csv.QUOTE_NONNUMERIC - Quote all fields that aren't numbers value.
csv.QUOTE_NONE – Don't quote anything in the output.
In the above snippet, we write the header part to the ‘file’ and iterate through each record in ‘product.product’. Take the needed element from the records and write that into the file.
Then you can read the file in the same function:
with open('export.csv', 'r', encoding="utf-8") as f2:
# file encode and store in a variable ‘data’
data = str.encode(f2.read(), 'utf-8')
Then return the data into a wizard and you can export the file through the wizard.
class ExportWizard(models.TransientModel):
_name = 'wiazrd.export.csv'
csv_data = fields.Binary()
filename = fields.Char()
# function will trigger from the export button in customer export
@api.multi
def export_customers(self):
# call the function generate csv files
data = self.env['export.csv'].export_product()
self.csv_data = base64.encodestring(data)
self.filename = 'export.csv'
return {
'type': 'ir.actions.act_url',
'url': "web/content/?model=wizard.export.csv&id=" + str(self.id) +
"&filename=export.csv&field=csv_data&download=true&filename=" + self.filename,
'target': 'self',
}