首先,在临时表页面的xml文件中添加import按钮
<group >
<field name="file" />
<newline/>
<button name="read_file" string="读取文件内容" type="object" class="oe_highlight" />
<button string="取消" class="oe_link" special="cancel"/>
</group>
其次,在py文件中实现导入和读取功能
导入功能由系统实现,读取由read_file函数实现
from datetime import datetime, timedelta
from odoo.tools import float_is_zero, float_compare, pycompat
from odoo import models, fields, api, _, SUPERUSER_ID
from odoo.exceptions import UserError, ValidationError
import base64
import xlrd
from io import BytesIO
from urllib import request
import json, sys
class PacktopoBlcodeImportPack(models.TransientModel):#存放导入TO向导的信息
_name = "packtopo.blcode.import.pack"
_description = "Wizard to import Test Orders"
#测试主表信息
blcode_id = fields.Many2one('packtopo.blcode', string='blcode') # 从父表单test中传递过来 , readonly=True
file = fields.Binary('文件')
pack = fields.Char('Pack编号')
pack_line_ids = fields.One2many(
comodel_name="packtopo.blcode.import.pack.line",
string="Packs04",
inverse_name="packtopo_blcode_import_pack_id", readonly=True)
@api.model
def default_get(self, fields): # 初始化向导窗口数据----------------
print('packtopo import default get')
rec = super().default_get(fields)
active_ids = self._context.get('active_ids')
active_model = self._context.get('active_model')
if not active_ids:
raise UserError(_(
"错误: 执行向导没有上下文环境数据 "))
request = self.env[active_model].browse(active_ids)
print('packtopo import default get middle active_ids[0]=', active_ids[0])
rec.update({
'blcode_id': active_ids[0],
# 'project_id': request[0].project_id,
# 'phase_id': request[0].phase_id,
})
print('packtopo import default get over')
return rec
@api.multi
def read_file(self): # 读取xls文件内容,写到btms.test.import.to.line中
"""
导入excel文件,按行读取数据并处理
:return: 导入结果视图
"""
print('packtopo import read_file')
#iserror=0 #默认数据正确
#errormsg='' #错误消息
self.pack_line_ids.unlink() #清空临时表中的数据
if not self.file:
return
# print(base64.decodebytes(self.file))
book = xlrd.open_workbook(file_contents=base64.decodebytes(self.file))
sh = book.sheet_by_name("Test Plan") #读取excel文件中的“Test Plan”这一Sheet
res_id = []
for rx in range(1, sh.nrows): #从1开始,跳过标题栏
#rowerror=0
#errormsg = '' # 错误消息
row = sh.row(rx)#遍历每一行数据---------对select字段也要做出错判断
#------------------------从restful api 获取pack图谱信息
print("row=", row)
print("row[0].value=", row[0].value) #row[0]表示第1个(列)
packid= row[0].value
url = "http://10.80.120.131:1819/mes/api/v1.0/dpca/" + row[0].value
print(url)
req = request.Request(url)
try:
resp = request.urlopen(req)
except:
print("Cannot remove service instance!")
sys.exit(1)
result = resp.read()
print(result)
result_json = json.loads(result)
#pack info
for i in range(len(result_json["packageList"])):
for j in range(len(result_json["packageList"][i]["moduleList"])):
for k in range(len(result_json["packageList"][i]["moduleList"][j]["cellList"])):
tmp_pack_row = {
'packname': result_json["packageList"][i]['global_pack_code'],
'encodedMode': result_json["packageList"][i]['global_pack_code'],
'moduleListLength': len(result_json["packageList"][i]["moduleList"]),
'offlineProductionTime': result_json["packageList"][i]['pack_produce_date'],
'shortPackCode': result_json["packageList"][i]['host_pack_code'],
'packtype': result_json["packageList"][i]['pack_bms_code'],
'modulename': result_json["packageList"][i]["moduleList"][j]['moduleCode'],
'moduletype': result_json["packageList"][i]["moduleList"][j]['module_batch_number'],
'cellListLength': len(result_json["packageList"][i]["moduleList"][j]["cellList"]),
'cellname': result_json["packageList"][i]["moduleList"][j]["cellList"][k]['cellCode'],
'cellnoname': result_json["packageList"][i]["moduleList"][j]["cellList"][k]['cellName'],
'celllevel': result_json["packageList"][i]["moduleList"][j]["cellList"][k]['celllevel'],
'celltype': result_json["packageList"][i]["moduleList"][j]["cellList"][k]['cell_part_num'],
'packtopo_blcode_import_pack_id': self.id,
#'iserror': rowerror,
#'errormsg': errormsg,
}
#生成 packtopo.import.pack.line---条目
#iserror=iserror+rowerror
self.env['packtopo.blcode.import.pack.line'].create(tmp_pack_row)
view_id = self.env.ref('packtopo.packtopo_blcode_import_pack').id
print('packtopo import read_file over view_id=', view_id)
return {
'type': 'ir.actions.act_window',
'view_type': 'form',
"view_mode": "form",
'res_model': 'packtopo.blcode.import.pack',
'target': 'current',
'res_id': self and self.id,
# 'view_id': view_id,
'views': [[view_id, "form"]],
'context': {'form_view_ref': 'packtopo.packtopo_blcode_import_pack'},
}