当前位置:网站首页>Excel import function of jeesite form page
Excel import function of jeesite form page
2022-07-07 08:08:00 【The sea of waves】
List of articles
jeeSite Of the form page Excel Import function
Preface
This article is using jeeSiteV4.3 Version of the framework based on Excel The import function of , If you haven't used jeeSite frame , You can ignore this article directly .
Use Excel There are actually three types of imported fields , One is a common type , Namely Excel What's written in , We just insert it directly into the database ; There is also a dictionary type ,Excel It's a key , We need to put the corresponding key ( Chinese characters ) Turn it into code ( Usually number ) ; The remaining one is object type , For example, employee type , Need to put Excel The position name in is converted to the position code in the database .
Next , Let's introduce .
Common type
You need to write @ExcelFields,sort yes Excel The order of the list fields ,align Is it in the middle?
@ExcelFields({
@ExcelField(title=" Project registration code ", attrName="engineeringRegistration", align= ExcelField.Align.CENTER, sort=10),
})
public Quality() {
this(null);
}
Dictionary type
You need to add on the basis of common types dictType=“professional_category”, This is the configuration in your dictionary data
@ExcelFields({
@ExcelField(title=" Major categories ", attrName="firstType",dictType="professional_category", align= ExcelField.Align.LEFT, sort=70),
@ExcelField(title=" Professional sub category ", attrName="secondType",dictType="professional_category", align= ExcelField.Align.CENTER, sort=80),
})
public Quality() {
this(null);
}
object type
You need to add on the basis of common types fieldType=, This represents the entity type , Will automatically send you Excel in The Chinese characters written in the list are converted into corresponding codes
@ExcelFields({
@ExcelField(title=" Company name ", attrName="office", align = ExcelField.Align.CENTER, sort=40,fieldType=OfficeType.class),
@ExcelField(title=" Name of project manager ", attrName="employee", align= ExcelField.Align.CENTER, sort=140,fieldType= EmployeeType.class),
})
public Quality() {
this(null);
}
We can see OfficeType This class ,EmployeeType There is no , We can also write one for our own reference .
OfficeType
/** * Copyright (c) 2013-Now http://jeesite.com All rights reserved. * No deletion without permission, or be held responsible to law. */
package com.jeesite.common.utils.excel.fieldtype;
import java.util.List;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.utils.EmpUtils;
/** * Field type conversion * @author ThinkGem * @version 2020-3-5 * @example fieldType = OfficeType.class */
public class OfficeType implements FieldType {
private List<Office> list;
public OfficeType() {
list = EmpUtils.getOfficeAllList();
}
/** * Get object value ( Import ) */
public Object getValue(String val) {
for (Office e : list){
if (StringUtils.trimToEmpty(val).equals(e.getOfficeName())){
return e;
}
}
return null;
}
/** * Set object value ( export ) */
public String setValue(Object val) {
if (val != null && ((Office)val).getOfficeName() != null){
return ((Office)val).getOfficeName();
}
return StringUtils.EMPTY;
}
}
EmployeeType
/** * Copyright (c) 2013-Now http://jeesite.com All rights reserved. * No deletion without permission, or be held responsible to law. */
package com.jeesite.common.utils.excel.fieldtype;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.utils.SpringUtils;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.service.EmployeeService;
import java.util.List;
/** * Field type conversion * @author ThinkGem * @version 2020-3-5 * @example fieldType = EmployeeType.class */
public class EmployeeType implements FieldType {
private List<Employee> list;
private static EmployeeService employeeService = SpringUtils.getBean(EmployeeService.class);;
public EmployeeType() {
Employee where = new Employee();
where.setStatus(Employee.STATUS_NORMAL);
list = employeeService.findList(where);
}
/** * Get object value ( Import ) */
public Object getValue(String val) {
for (Employee e : list){
if (StringUtils.trimToEmpty(val).equals(e.getEmpName())){
return e;
}
}
return null;
}
/** * Set object value ( export ) */
public String setValue(Object val) {
if (val != null && ((Employee)val).getEmpName() != null){
return ((Employee)val).getEmpName();
}
return StringUtils.EMPTY;
}
}
thus , Configuration on entity type , We're done with . Next , Go to the front page
front end
jeeSite There is no need for us to configure Excel Templates , It will be based on ExcelFields Automatic configuration Excel, When I click download , There will be Excel
<div class="box-tools pull-right">
<a href="#" class="btn btn-default" id="btnSearch" title="${text(' Inquire about ')}"><i class="fa fa-filter"></i> ${text(' Inquire about ')}</a>
<!--<a href="#" class="btn btn-default" id="btnExport"><i class="glyphicon glyphicon-export"></i> ${text(' export ')}</a>-->
<a href="#" class="btn btn-default" id="btnImport"><i class="glyphicon glyphicon-import"></i> ${text(' Import ')}</a>
</div>
//js
$('#btnImport').click(function(){
js.layer.open({
type: 1,
area: ['400px'],
title: '${text(" Import quality inspection task data ")}',
resize: false,
scrollbar: true,
content: js.template('importTpl'),
success: function(layero, index){
layero.find('input[type="checkbox"]').iCheck();
},
btn: ['<i class="fa fa-check"></i> ${text(" Import ")}',
'<i class="fa fa-remove"></i> ${text(" close ")}'],
btn1: function(index, layero){
var form = {
inputForm: layero.find('#inputForm'),
file: layero.find('#file').val()
};
if (form.file == '' || (!js.endWith(form.file, '.xls') && !js.endWith(form.file, '.xlsx'))){
js.showMessage("${text(' The file is incorrect , Please select suffix “xls” or “xlsx” The file of .')}", null, 'warning');
return false;
}
js.ajaxSubmitForm(form.inputForm, function(data){
js.showMessage(data.message);
if(data.result == Global.TRUE){
js.layer.closeAll();
}
page();
}, "json");
return true;
}
});
});
// The configuration file
<script id="importTpl" type="text/template">//<!-- <form id="inputForm" action="${ctx}/importData" method="post" enctype="multipart/form-data" class="form-horizontal mt20 mb10" style="overflow:auto;max-height:200px;"> <div class="row"> <div class="col-xs-12 col-xs-offset-1"> <input type="file" id="file" name="file" class="form-file"/> <div class="mt10 pt5"> <a href="${ctx}/importTemplate" class="btn btn-default btn-xs"><i class="fa fa-file-excel-o"></i> ${
text(' Download the template ')}</a> </div> <font color="red" class="pull-left mt10"> ${
text(' Tips : Only import is allowed “xls” or “xlsx” Format file !')} </font> </div> </div> </form> //--></script>
Back end
Controller
/** * Download and import user data template */
@RequestMapping(value = "importTemplate")
public void importTemplate(HttpServletResponse response) {
Quality empUser = new Quality();
User user = UserUtils.getUser();
List<Quality> list = ListUtils.newArrayList(empUser);
String fileName = " Task data template .xlsx";
try(ExcelExport ee = new ExcelExport(" Mission data ", Quality.class, ExcelField.Type.IMPORT)){
ee.setDataList(list).write(response, fileName);
}
}
/** * Import user data */
@ResponseBody
@PostMapping(value = "importData")
public String importData(MultipartFile file, String updateSupport) {
try {
boolean isUpdateSupport = Global.YES.equals(updateSupport);
String message = qualityService.importData(file, isUpdateSupport);
return renderResult(Global.TRUE, "posfull:"+message);
} catch (Exception ex) {
return renderResult(Global.FALSE, "posfull:"+ex.getMessage());
}
}
Service
/** * Import user data * @param file Imported user data file * @param isUpdateSupport Update support , If it already exists , Update the data */
@Transactional(readOnly=false)
public String importData(MultipartFile file, Boolean isUpdateSupport) {
if (file == null){
throw new ServiceException(text(" Please select the imported data file !"));
}
int successNum = 0; int failureNum = 0;
StringBuilder successMsg = new StringBuilder();
StringBuilder failureMsg = new StringBuilder();
try(ExcelImport ei = new ExcelImport(file, 2, 0)){
List<Quality> list = ei.getDataList(Quality.class);
for (Quality quality : list) {
try{
// Verify the data file
ValidatorUtils.validateWithException(quality);
// Verify that the Department is empty
if (StringUtils.isBlank(quality.getOffice().getOfficeName())) {
failureNum++;
failureMsg.append("<br/>" + failureNum
+ " Import failed : Company cannot be empty ");
continue;
}
if (StringUtils.isBlank(quality.getEmployee().getEmpName())) {
failureNum++;
failureMsg.append("<br/>" + failureNum
+ " Import failed : The project manager cannot be empty ");
continue;
}
// Currently logged in by
String createby = UserUtils.getUser().getUserName();
quality.setCreateUser(createby);
quality.setCreateTime(new Date());
this.save(quality);
successNum++;
successMsg.append("<br/>" + successNum + " Task information " + " Successful import ");
} catch (Exception e) {
failureNum++;
String msg = "<br/>" + failureNum + " Import failed :";
if (e instanceof ConstraintViolationException){
ConstraintViolationException cve = (ConstraintViolationException)e;
for (ConstraintViolation<?> violation : cve.getConstraintViolations()) {
msg += Global.getText(violation.getMessage()) + " ("+violation.getPropertyPath()+")";
}
}else{
msg += e.getMessage();
}
failureMsg.append(msg);
logger.error(msg, e);
}
}
} catch (Exception e) {
failureMsg.append(e.getMessage());
logger.error(e.getMessage(), e);
}
if (failureNum > 0) {
failureMsg.insert(0, " I'm sorry , Import failed ! common " + failureNum + " The data format is incorrect , Error is as follows :");
throw new ServiceException(failureMsg.toString());
}else{
successMsg.insert(0, " Congratulations , The data has been imported successfully ! common " + successNum + " strip , The data are as follows :");
}
return successMsg.toString();
}
Last
Here we are ,jeeSite Of the form page Excel Import function , It's done , I hope I can help you . Welcome to comment , give the thumbs-up , forward .
边栏推荐
- C language communication travel card background system
- Shell 脚本的替换功能实现
- Ansible
- 通俗易懂单点登录SSO
- [UVM foundation] what is transaction
- LeetCode简单题之找到一个数字的 K 美丽值
- Few shot Learning & meta learning: small sample learning principle and Siamese network structure (I)
- Niu Mei's mathematical problem --- combinatorial number
- Recursive construction of maximum binary tree
- [advanced digital IC Verification] command query method and common command interpretation of VCs tool
猜你喜欢
【数字IC验证快速入门】12、SystemVerilog TestBench(SVTB)入门
Thinkcmf6.0安装教程
【数字IC验证快速入门】10、Verilog RTL设计必会的FIFO
[matlab] when matrix multiplication in Simulink user-defined function does not work properly, matrix multiplication module in module library can be used instead
Real time monitoring of dog walking and rope pulling AI recognition helps smart city
Linux server development, MySQL index principle and optimization
复杂网络建模(一)
2022 simulated examination question bank and online simulated examination of tea master (primary) examination questions
Empire CMS collection Empire template program general
青龙面板-今日头条
随机推荐
It took "7" years to build the robot framework into a micro service
Introduction to basic components of wechat applet
Who has docker to install MySQL locally?
基于Pytorch 框架手动完成线性回归
【数字IC验证快速入门】14、SystemVerilog学习之基本语法1(数组、队列、结构体、枚举、字符串...内含实践练习)
芯片 设计资料下载
Quickly use Jacobo code coverage statistics
paddlepaddle 29 无模型定义代码下动态修改网络结构(relu变prelu,conv2d变conv3d,2d语义分割模型改为3d语义分割模型)
Force buckle 145 Binary Tree Postorder Traversal
Record a stroke skin bone error of the skirt
Few shot Learning & meta learning: small sample learning principle and Siamese network structure (I)
Bugku CTF daily one question chessboard with only black chess
追风赶月莫停留,平芜尽处是春山
Linux server development, MySQL index principle and optimization
Pytorch(六) —— 模型调优tricks
2022制冷与空调设备运行操作复训题库及答案
mysql多列索引(组合索引)特点和使用场景
Linux server development, redis protocol and asynchronous mode
[Matlab] Simulink 自定义函数中的矩阵乘法工作不正常时可以使用模块库中的矩阵乘法模块代替
探索干货篇!Apifox 建设思路