Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and then write on a xlsx file

I am new to python and odoo. I came across a scenario that i want to create a excel file first from my dynamic records and then want to save it to ir.attachment table. So that i can link that as an attachment in email.

Here is what i tried, but its not writing into the file

    workbook = xlsxwriter.Workbook('demo.xlsx')
    worksheet = workbook.add_worksheet()
    worksheet.set_column('A:A', 20)
    bold = workbook.add_format({'bold': True})
    worksheet.write('A1', 'Hello')
    worksheet.write('A2', 'World', bold)
    worksheet.write(2, 0, 123)
    worksheet.write(3, 0, 123.456)
    workbook.close()

Update

I am able to create the xlsx file, actullay it was my path issue. Now i just want to know that how to add that file in ir.attachment

like image 402
Ancient Avatar asked Dec 19 '17 17:12

Ancient


1 Answers

You can create xlsx file dynamically and attach via email.

from cStringIO import StringIO
import base64
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()
worksheet.set_column('A:A', 20)
bold = workbook.add_format({'bold': True})
worksheet.write('A1', 'Hello')
worksheet.write('A2', 'World', bold)
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)
fp = StringIO()
workbook.save(fp)
fp.seek(0)
datas = base64.encodestring(fp.read())
file_name = "name_%s" %(time.strftime('%Y%m%d%H%M%S.xlsx'))
attachment=[]
attachment_data = {
    'name':file_name,
    'datas_fname':file_name,
    'datas':datas,
    'res_model':"modelname",
    }
attachment.append(self.env['ir.attachment'].create(attachment_data).id)

mail_obj=self.env['mail.mail']
mail_template=self.env.ref('mail_template_id')        
msg_ids=mail_template.send_mail(id of object)
msgs=mail_obj.browse(msg_ids)
msgs.write({'attachment_ids': [(6, 0, attachment)]})

In above code we have create one worksheet record and after that create attachment record.

You need to give name,datas_fname,datas,res_model to create attachment. you can also give res_id to create attachment, after that system will automatic visible attachment inside that model and record.

After create attachment you can use dynamically in the email.

This may help you.

like image 196
Emipro Technologies Pvt. Ltd. Avatar answered Oct 14 '22 08:10

Emipro Technologies Pvt. Ltd.