当前位置:网站首页>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 .
边栏推荐
- 芯片 設計資料下載
- paddlepaddle 29 无模型定义代码下动态修改网络结构(relu变prelu,conv2d变conv3d,2d语义分割模型改为3d语义分割模型)
- C语言队列
- Rust versus go (which is my preferred language?)
- Record a stroke skin bone error of the skirt
- Merging binary trees by recursion
- Explore dry goods! Apifox construction ideas
- Ansible
- 调用 pytorch API完成线性回归
- 【踩坑系列】uniapp之h5 跨域的问题
猜你喜欢
Open source ecosystem | create a vibrant open source community and jointly build a new open source ecosystem!
These five fishing artifacts are too hot! Programmer: I know, delete it quickly!
QT learning 26 integrated example of layout management
Ansible
LeetCode简单题之找到一个数字的 K 美丽值
mysql多列索引(组合索引)特点和使用场景
【数字IC验证快速入门】12、SystemVerilog TestBench(SVTB)入门
padavan手动安装php
央视太暖心了,手把手教你写HR最喜欢的简历
MySQL multi column index (composite index) features and usage scenarios
随机推荐
复杂网络建模(三)
基于Pytorch 框架手动完成线性回归
船载雷达天线滑环的使用
央视太暖心了,手把手教你写HR最喜欢的简历
It took "7" years to build the robot framework into a micro service
offer收割机:两个长字符串数字相加求和(经典面试算法题)
探索干货篇!Apifox 建设思路
JS quick start (I)
Yugu p1020 missile interception (binary search)
复杂网络建模(一)
【数字IC验证快速入门】14、SystemVerilog学习之基本语法1(数组、队列、结构体、枚举、字符串...内含实践练习)
芯片资料 网站 易特创芯
B. Value sequence thinking
Linux server development, MySQL index principle and optimization
C语言二叉树与建堆
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after conne
Quickly use Jacobo code coverage statistics
These five fishing artifacts are too hot! Programmer: I know, delete it quickly!
[UVM foundation] what is transaction
互动送书-《Oracle DBA工作笔记》签名版