[分享]销售订单从Excel导入模版
-
本着开源共享的精神,现将我们已经用了很成熟的销售订单从Excel导入模版做成一个Demo模块共享给大家,搞懂了这个,其他的什么采购订单,员工信息之类的都可以用类似的方法完成.废话不多说,简要给大家介绍一下代码的含义:
1.首先定义要上传的字段,为bin类型:<br />_columns={<br /> 'data':fields.binary('File'), <br />}<br />
2.然后在view里定义该字段并附件一个导入按钮:<br /><?xml version="1.0" encoding="utf-8"?><br /><openerp><br /> <data><br /> <record id="rainsoft_order_form" model="ir.ui.view"><br /> <field name="name">rainsoft.order.form</field><br /> <field name="model">sale.order</field><br /> <field name="inherit_id" ref="sale.view_order_form"/><br /> <field name="arch" type="xml"><br /> <xpath expr="//field[@name='order_line']" position="before"><br /> <group><br /> <group><br /> <field name='data'/><br /> </group> <br /> <group> <br /> <button name='import_file' string='Import' type='object' class='oe_edit_only' states="draft" /><br /> </group><br /> </group><br /> </xpath><br /> </field><br /> </record><br /> </data><br /></openerp><br />
3.在相应的py文件中定义对这个button处理的逻辑,也就是我们要进行读取Excel并写入订单行的代码:<br />def import_file(self,cr,uid,ids,context=None):<br /> for wiz in self.browse(cr,uid,ids):<br /> if not wiz.data:continue<br /> excel = xlrd.open_workbook(file_contents=base64.decodestring(wiz.data))<br /> sheets = excel.sheets()<br /> for sh in sheets:<br /> if sh.name:<br /> lines=[]<br /> for row in range(1,sh.nrows):<br /> if sh.cell(row,1).value and sh.cell(row,5).value:<br /> product_no = int(str(sh.cell(row,1).value).strip().split('.')[0])<br /> product_amount=sh.cell(row,5).value<br /> product_price =sh.cell(row,6).value<br /> product_method=sh.cell(row,12).value<br /> if product_method == u'订单':<br /> product_method='make_to_order'<br /> else:<br /> product_method='make_to_stock'<br /> <br /> products = self.pool.get('product.product').search(cr,uid,[('default_code','=',product_no)],context=context)<br /> _logger.info("importing product_no:"+str(product_no)+";products:"+str(products))<br /> if len(products)>0 and product_amount>0 and product_amount:<br /> product = self.pool.get('product.product').browse(cr,uid,products[0],context=context)<br /> line={<br /> 'order_id':ids[0],<br /> 'name':product.name,<br /> 'product_id':product.id,<br /> 'price_unit':product_price,<br /> 'product_uom':product.uom_id.id,<br /> 'product_uom_qty':product_amount,<br /> 'type':product_method,<br /> 'state':'draft',<br /> }<br /> self.pool.get('sale.order.line').create(cr,uid,line,context)<br /> else:<br /> _logger.info("product insert failed. No:"+str(product_no))<br /> _logger.info("probably caused by 1.len(products):"+str(len(products))+",2.product_amount:"+str(product_amount))<br /> else:<br /> _logger.info('row 1 and row 5 is invalid! Error Column 1:'+str(sh.cell(row,1).value)+";Error Column 2:"+str(sh.cell(row,5).value))<br />
导入Excel这里用到的是xlrd库,效果见附件图
Demo地址(附带Excel文件):https://github.com/kevin8909/sale_from_excel