当前位置:网站首页>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 .
边栏推荐
- Thinkcmf6.0 installation tutorial
- Cnopendata list data of Chinese colleges and Universities
- Qt学习28 主窗口中的工具栏
- [quickstart to Digital IC Validation] 15. Basic syntax for SystemVerilog Learning 2 (operator, type conversion, loop, Task / Function... Including practical exercises)
- Pytorch(六) —— 模型调优tricks
- 运放电路的反馈电阻上并联一个电容是什么作用
- 数据库实时同步利器——CDC(变化数据捕获技术)
- 调用 pytorch API完成线性回归
- Lattice coloring - matrix fast power optimized shape pressure DP
- Linux server development, SQL statements, indexes, views, stored procedures, triggers
猜你喜欢
随机推荐
Explore dry goods! Apifox construction ideas
青龙面板--花花阅读
[advanced digital IC Verification] command query method and common command interpretation of VCs tool
Introduction à l'objet blob
王爽 《汇编语言》之寄存器
offer收割机:两个长字符串数字相加求和(经典面试算法题)
Pytorch(六) —— 模型调优tricks
[matlab] when matrix multiplication in Simulink user-defined function does not work properly, matrix multiplication module in module library can be used instead
Open source ecosystem | create a vibrant open source community and jointly build a new open source ecosystem!
Thinkcmf6.0安装教程
Myabtis_Plus
JS cross browser parsing XML application
Recursive construction of maximum binary tree
运放电路的反馈电阻上并联一个电容是什么作用
JSON data flattening pd json_ normalize
【數字IC驗證快速入門】15、SystemVerilog學習之基本語法2(操作符、類型轉換、循環、Task/Function...內含實踐練習)
Recursive method to construct binary tree from preorder and inorder traversal sequence
[quick start of Digital IC Verification] 17. Basic grammar of SystemVerilog learning 4 (randomization)
Recursive method to verify whether a tree is a binary search tree (BST)
【无标题】