odoo.define('export_module.export_xls', function (require) {
'use strict';
var ListView = require('web.ListView');
var Model = require('web.Model');
var framework = require('web.framework');
var crash_manager = require('web.crash_manager');
ListView.include({
render_buttons: function () {
this._super.apply(this, arguments);
var self = this;
// Export data handle
this.$buttons.on('click', 'button.export_xls', function () {
var export_columns_string = []; // The field name when export
var export_columns_names = []; // The field data when export
for (var i = 0; i < self.columns.length; i++) {
export_columns_string.push(self.columns[i].string);
export_columns_names.push(self.columns[i].name)
}
var model = new Model(self.model);
var list_ids = self.groups.get_selection().ids;
// According to the field query data
model.query(export_columns_names).filter([['id', 'in', list_ids]]).all().then(function (r) {
if (r.length > 0) {
var export_rows = [];
for (var i = 0; i < r.length; i++) {
var rows = []
for (var j = 0; j < export_columns_names.length; j++) {
rows.push(r[i][export_columns_names[j]])
}
export_rows.push(rows)
}
}
// Call controllers to download data
// console.log(export_columns_string, JSON.stringify(export_rows))
console.log(export_columns_string, export_rows);
framework.blockUI();
self.session.get_file({
url: '/export_module/export/xls_data',
data: {
data: JSON.stringify({
model: self.model,
headers: export_columns_string,
rows: export_rows
})
},
complete: framework.unblockUI,
error: crash_manager.rpc_error.bind(crash_manager)
});
});
});
}
});
});
templates.xml
controllers.py
# -*- coding: utf-8 -*-
import json
import xlwt
import operator
from odoo import http
from odoo.http import request
from odoo.addons.web.controllers.main import serialize_exception
from odoo.addons.web.controllers.main import CSVExport, content_disposition, Export, ExcelExport
try:
from cStringIO import StringIO
except ImportError:
import cStringIO as StringIO
class ExcelExportView(ExcelExport):
def __getattribute__(self, name):
if name == 'fmt':
raise AttributeError()
return super(ExcelExportView, self).__getattribute__(name)
def rows_data_process(self, rows_data):
if rows_data:
for row in rows_data:
for k, v in enumerate(row):
if isinstance(v, list):
row[k] = v[1]
return rows_data
return []
@http.route('/export_module/export/xls_data', type='http', auth='user')
def export_xls_data(self, data, token):
data = json.loads(data)
model = data.get('model', [])
columns_headers = data.get('headers', [])
rows = self.rows_data_process(data.get('rows'))
return request.make_response(
self.from_data(columns_headers, rows),
headers=[
('Content-Disposition', 'attachment; filename="%s"'
% self.filename(model)),
('Content-Type', self.content_type)
],
cookies={'fileToken': token}
)
class Controller(http.Controller):
@http.route('/export_module/export/template', type='http', auth="user")
@serialize_exception
def download_template(self, data, token):
params = json.loads(data)
model, fields = operator.itemgetter('model', 'fields')(params)
columns_headers = [val['label'].strip() for val in fields]
return request.make_response(self.from_data(columns_headers),
headers=[('Content-Disposition',
http.content_disposition(model + '.xls')),
('Content-Type', 'application/vnd.ms-excel')],
cookies={'fileToken': token})
def from_data(self, fields):
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Sheet 1')
for i, fieldname in enumerate(fields):
worksheet.write(0, i, fieldname)
worksheet.col(i).width = 4000
fp = StringIO()
workbook.save(fp)
fp.seek(0)
data = fp.read()
fp.close()
return data
Import CSV File
import_wizard.py
# -*- coding: utf-8 -*-
import os
import csv
import base64
import logging
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from odoo import api, fields, models, tools, _
from odoo.exceptions import except_orm
_logger = logging.getLogger(__name__)
class AlertInfo(except_orm):
pass
class ImportWizard(models.TransientModel):
"""
Import customer bills and change orders approval state
"""
_name = 'import.wizard'
data = fields.Binary(string=u'文件', required=True)
filename = fields.Char(string=u'文件名称', required=True)
@api.multi
def import_bills(self):
this = self[0]
fileformat = os.path.splitext(this.filename)[-1][1:].lower()
if fileformat != 'csv':
error = 'CSV files only'
raise AlertInfo(_("Failed"), error)
try:
self._cr.execute('SAVEPOINT ue_import')
new_data = list(self._read_csv())
_logger.info('start import')
self._read_bills(new_data)
except Exception as e:
_logger.exception('Import Error')
self._cr.execute('ROLLBACK TO SAVEPOINT ue_import')
_logger.info('roll back ue import')
raise AlertInfo(_("Failed"), tools.ustr(e))
else:
self._cr.execute('RELEASE SAVEPOINT ue_import')
_logger.info("import done")
return {
'name': _('Success'),
'view_type': 'form',
'view_mode': 'form',
'view_id': self.env.ref('module_name.import_form_view_success').id,
'res_model': 'import.wizard',
'domain': [],
'context': dict(self._context, active_ids=self.ids),
'type': 'ir.actions.act_window',
'target': 'new',
'res_id': self.id,
}
def _read_csv(self):
csv_data = base64.decodestring(self.data)
try:
csv_data = csv_data.decode('utf-8')
except UnicodeDecodeError:
csv_data = csv_data.decode('gbk')
csv_data = csv_data.encode('utf-8')
csv_iterator = csv.reader(StringIO(csv_data))
csv_u_iter = ([item.decode('utf-8') for item in row] for row in csv_iterator if
any(x for x in row if x.strip()))
try:
header = next(csv_u_iter)
except StopIteration:
return
else:
for line in csv_u_iter:
yield dict(zip(header, line))
def _read_bills(self, new_data):
for data in new_data:
import_name = data.get(u'订单号', '')
customer_order_obj = self.env['customer.order'].search([('name', '=', import_name)])
if customer_order_obj.state == 'done':
approval_state = data.get(u'审批状态')
if approval_state == u'成功' or approval_state == '1':
selection = '1'
else:
selection = '0'
customer_order_obj.write({'approval_state': selection})
import_views.xml
Import Bills Change Statusimport.wizardImport Billsir.actions.act_windowimport.wizardformformnewImport Bills Change Status Successimport.wizard
ir_bills.xml
Results the template for approval of the billscustomer.ordernamecustomer_idapproval_state
controllers.py
# -*- coding: utf-8 -*-
from odoo.http import request
from odoo import http
from odoo.addons.web.controllers.main import CSVExport, content_disposition, Export, ExcelExport
class DownloadModels(http.Controller):
@http.route('/module_name/download_models/template_csv', auth='public', csrf=False)
def bill_template_csv(self):
"""
Download customer bill template file
"""
records = request.env['j.order'].search([], limit=3)
name_list = Export().namelist('j.order', request.env.ref('module_name.import_bills_template').sudo().id)
field_names = [i['name'] for i in name_list]
field_labels = [i['label'] for i in name_list]
data = records.export_data(field_names).get('datas', [])
d = CSVExport().from_data(field_labels, data)
return http.Response(d, headers=[('Content-Disposition', content_disposition('bills_info.csv')),
('Content-Type', 'application/vnd.ms-excel')])
在系统运行后,在线程快照里总是看到线程池的名字为pool-xx,这样导致很不好定位,怎么给线程池一个有意义的名字呢。参照ThreadPoolExecutor类的ThreadFactory,自己实现ThreadFactory接口,重写newThread方法即可。参考代码如下:
public class Named
错误: IE 中"HTML Parsing Error:Unable to modify the parent container element before the child element is closed"
现象: 同事之间几个IE 测试情况下,有的报这个错,有的不报。经查询资料后,可归纳以下原因。
PropertyPlaceholderConfigurer是个bean工厂后置处理器的实现,也就是BeanFactoryPostProcessor接口的一个实现。关于BeanFactoryPostProcessor和BeanPostProcessor类似。我会在其他地方介绍。PropertyPlaceholderConfigurer可以将上下文(配置文件)中的属性值放在另一个单独的标准java P
创建一个类
public class ContextInitListener implements ServletContextListener
使得该类成为一个监听器。用于监听整个容器生命周期的,主要是初始化和销毁的。
类创建后要在web.xml配置文件中增加一个简单的监听器配置,即刚才我们定义的类。
<listener>
<des
http://developer.apple.com/iphone/library/qa/qa2009/qa1649.html
Excerpt:
You are getting this warning because you probably added your Info.plist file to your Copy Bundle
hi,
自己在做工程的时候,遇到批量插入数据的数据修复场景。我的思路是在插入前准备一个临时表,临时表的整理就看当时的选择条件了,临时表就是要插入的数据集,最后再批量插入到数据库中。
WITH tempT AS (
SELECT
item_id AS combo_id,
item_id,
now() AS create_date
FROM
a