DEV Community

Jeevachaithanyan Sivanandan
Jeevachaithanyan Sivanandan

Posted on

Odoo : create CSV file and download

a wizard method to download some information of the sale order - order lines to csv file

this method have features as :

  1. get current sale order
  2. get product id and product quantities from sale order lines
  3. write those into a csv file
  4. initiate the download of csv file
  5. auto close the wizard
import base64
import csv
from io import StringIO

    def action_download_template(self):
        sale_order = self.get_current_sale_order()
        dynamic_filename = f"so_{sale_order.id}_template.csv"

        partner_id = sale_order.partner_id.id if sale_order.partner_id else ''
        data = [["Partner ID", "Product ID", "Product Quantity"]]
        for line in sale_order.order_line:
            data.append([partner_id, line.product_template_id.default_code, line.product_uom_qty])

        csv_data = StringIO()
        writer = csv.writer(csv_data)
        writer.writerows(data)
        csv_data.seek(0)

        csv_base64 = base64.b64encode(csv_data.getvalue().encode('utf-8'))
        csv_data.close()

        self.write({'csv_file': csv_base64, 'file_name': dynamic_filename})

        return {
            'type': 'ir.actions.act_url',
            'url': f"/web/content/?model=sale.order.import.wizard&id={self.id}&field=csv_file&download=true&filename={dynamic_filename}",
            'target': 'self',
            'next': {'type': 'ir.actions.act_window_close'},
        }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)