This question has been flagged
2 Replies
16547 Views

Hello

I have seen python script importing data from csv file into OpenERP . But is their python script which allows me to export existing openerp data into csv file or in plain format?

Thanks

Avatar
Discard

yup me also want to know it, can anyone tell me where or how by using python code to export the data

Best Answer

It's simple, just use csv lib (example below):

import csv
import base64
with open('employee_file.csv', mode='w') as employee_file:
    employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    employee_writer.writerow(['John Smith', 'Accounting', 'November'])
    employee_writer.writerow(['Erica Meyers', 'IT', 'March'])

Probably you'll need to use StringIO to not save it as a file, but to a string and then to encode to base64 and save it to a binary field. I normally make import export wizards for this. Don't have any example for csv, mostly creating excel files. But the link below will show how it's done.

\Using StringIO and csv 

\https://stackoverflow.com/questions/9157314/how-do-i-write-data-into-csv-format-as-string-not-file

EDIT:

This is an example for a model method, the model needs to have a field named file_field, like in the comment.

Not sure if it'll work just copy paste, because this are just few lines of my complex method. I've just kept the basis

import xlwt
import StringIO
import base64


def create_excel(self, ids)
  tasks = self.env['project.task'].sudo().browse(ids)

  stream = StringIO.StringIO()
  book = xlwt.Workbook(encoding='utf-8')
  sheet = book.add_sheet(u'{}'.format(u'My Sheet'))

  row = 1
  cell = 0

  for task in tasks:
    sheet.write(row, cell, task.name)
    row += 1

  book.save(stream)

  # file_field = fields.Binary()
  self.file_field = base64.encodestring(stream.getvalue())

Avatar
Discard

do you got a link with a guide to ceate excel reports?

I've edited my answer with the basis for excel writing and saving into binary field

What about executing python code with "Automated Actions"? There is an option to execute python code but can we paste your code over there?

never used automated actions. only used scheduled actions... that works like cronjob on linux. There you only need to put the method and not the whole code. But I wouldn't do anything that creates files and writes them in the database as a scheduled action. It'll bloat your DB. If anything in my answer is helpfull you can upvote it.