pom.xml
。
<!-- poi依赖 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
entity
。
package com.ysd.demo1.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.ysd.demo1.util.ExcelDesc;
import java.io.Serializable;
/**
*
*
*
*
* @author jmf
* @since 2020-03-31
*/
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 学生ID
*/
@TableId(value = "student_id", type = IdType.AUTO)
private Integer studentId;
/**
* 卡号
*/
@ExcelDesc("卡号")
private Integer cardNo;
/**
* 姓名
*/
@ExcelDesc("学生姓名")
private String studentName;
/**
* 性别
*/
@ExcelDesc("性别")
private String studentSex;
/**
* 年龄
*/
@ExcelDesc("年龄")
private String studentAge;
/**
* 需要:专业,系名称
*/
private Integer professionalId;
/**
* 备注
*/
@ExcelDesc("备注")
private String studentNote;
/**
* 逻辑删除
*/
@TableLogic
private Integer del;
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public Integer getCardNo() {
return cardNo;
}
public void setCardNo(Integer cardNo) {
this.cardNo = cardNo;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentSex() {
return studentSex;
}
public void setStudentSex(String studentSex) {
this.studentSex = studentSex;
}
public String getStudentAge() {
return studentAge;
}
public void setStudentAge(String studentAge) {
this.studentAge = studentAge;
}
public Integer getProfessionalId() {
return professionalId;
}
public void setProfessionalId(Integer professionalId) {
this.professionalId = professionalId;
}
public String getStudentNote() {
return studentNote;
}
public void setStudentNote(String studentNote) {
this.studentNote = studentNote;
}
public Integer getDel() {
return del;
}
public void setDel(Integer del) {
this.del = del;
}
@Override
public String toString() {
return "Student{" +
"studentId=" + studentId +
", cardNo=" + cardNo +
", studentName=" + studentName +
", studentSex=" + studentSex +
", studentAge=" + studentAge +
", professionalId=" + professionalId +
", studentNote=" + studentNote +
", del=" + del +
"}";
}
/**
* 系名称
*/
@TableField(exist = false)
@ExcelDesc("系名称")
private String systemName;
/**
* 专业名称
*/
@TableField(exist = false)
@ExcelDesc("专业名称")
private String professionalName;
/**
* 学历
*/
@TableField(exist = false)
@ExcelDesc("学历")
private String professionalDegree;
public String getSystemName() {
return systemName;
}
public void setSystemName(String systemName) {
this.systemName = systemName;
}
public String getProfessionalName() {
return professionalName;
}
public void setProfessionalName(String professionalName) {
this.professionalName = professionalName;
}
public String getProfessionalDegree() {
return professionalDegree;
}
public void setProfessionalDegree(String professionalDegree) {
this.professionalDegree = professionalDegree;
}
}
service
。
/**
* 批量导入时的 保存老师及其对应的科室
* @param list 读取的List集合
* @return
*/
boolean saveBatchCustom(List<Student> list);
List<Student> getAll();
serviceimpl
。
/**
* 事务传播属性为嵌套:如果没有,就新建一个事务;如果有,就在当前事务中嵌套其他事务
* @param list 读取的List集合
* @return
*/
@Override
@Transactional(propagation = Propagation.NESTED)
public boolean saveBatchCustom(List<Student> list) {
Map<String, List<Student>> maps = toMap(list);
boolean result = false;
//声明外键id
Integer professionalId;
for(String str:maps.keySet()){
//创建外键数组
String[] professionalKey = str.split(",");
Professional professional = new Professional();
professional.setSystemName(professionalKey[0]);
professional.setProfessionalName(professionalKey[1]);
professional.setProfessionalDegree(professionalKey[2]);
//查询外键是否存在
QueryWrapper<Professional> queryWrapper = new QueryWrapper();
queryWrapper
.eq("system_name",professionalKey[0])
.eq("professional_name",professionalKey[1])
.eq("professional_degree",professionalKey[2]);
Professional professionalData = professionalMapper.selectOne(queryWrapper);
if(professionalData==null){
//否:新建
professionalMapper.insert(professional);
professionalId = professional.getProfessionalId();
}else{
//是:赋值
professionalId = professionalData.getProfessionalId();
}
for(Student student:maps.get(str)){
student.setProfessionalId(professionalId);
}
result = saveBatch(maps.get(str));
}
return false;
}
@Override
public List<Student> getAll() {
return baseMapper.getAll();
}
/**
* 将list集合转换为map
* @param list
* @return
*/
private Map<String,List<Student>> toMap(List<Student> list){
Map<String,List<Student>> map = new HashMap<>();
//定义存放相关外键内容的String
String professionalKey = "";
for(Student student:list){
//依次存放系,专业,学历
professionalKey =
student.getSystemName()+","+
student.getProfessionalName()+","+
student.getProfessionalDegree();
if(!map.containsKey(professionalKey)){
List<Student> students = new ArrayList<Student>();
students.add(student);
map.put(professionalKey,students);
}else{
map.get(professionalKey).add(student);
}
}
return map;
}
controller
。
@RequestMapping("/upload")
@ResponseBody
public ResultBody uploadStudent(@RequestParam("file") MultipartFile multipartFile){
List<Student> list = ExcelUtil.getBeanList(Student.class,multipartFile);
List<Student> studentList = iStudentService.list();
List<Professional> professionalList = iProfessionalService.list();
List<Student> none = new ArrayList<>();
//卡号记录去重
for (int i = 0; i < list.size(); i++) {
boolean flag = false;
for (int j = 0; j < studentList.size(); j++) {
if (
list.get(i).getCardNo().equals(studentList.get(j).getCardNo())
) {
flag = true;
break;
}
}
if (flag) {
continue;
}
none.add(list.get(i));
}
if(iStudentService.saveBatchCustom(none)){
return ResultBody.success();
}
return ResultBody.error("-1","操作失败");
}
@RequestMapping("/export")
public void exportStudent(HttpServletResponse response) {
String filename = "fileStudent.xlsx";
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
try {
OutputStream out = response.getOutputStream();
List<List<Object>> rows = new ArrayList<>();
List<Object> head = Arrays.asList("卡号", "学生姓名", "性别", "年龄", "系名称", "专业名称", "学历", "备注");
rows.add(head);
List<Student> all = iStudentService.getAll();
for (Student student : all) {
List<Object> columns = new ArrayList<>();
columns.add(student.getCardNo());
columns.add(student.getStudentName());
columns.add(student.getStudentSex());
columns.add(student.getStudentAge());
columns.add(student.getSystemName());
columns.add(student.getProfessionalName());
columns.add(student.getProfessionalDegree());
columns.add(student.getStudentNote());
rows.add(columns);
}
ExcelUtil.export("fileStudent", rows, out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
mapper.xml
。
<select id="getAll" resultType="com.ysd.demo1.entity.Student">
SELECT s.*,
p.`system_name` as systemName,
p.`professional_name` as professionalName,
p.`professional_degree` as professionalDegree
from student s ,professional p
where s.professional_id = p.professional_id
</select>
前台js
。
//顶部工具栏事件
table.on('toolbar(test)', function (obj) {
switch (obj.event) {
case "add":
layer.open({
type: 2
,title: '添加'
,content: 'student_add'
,area: ['500px', '400px']
,btn: ['确定', '取消']
,yes: function(index, layero){
//index当前层索引、layero当前层DOM对象。
//得到iframe页的窗口对象
var iframeWindow = window['layui-layer-iframe'+ index]
//得到submit按钮对象
,submit = layer.getChildFrame('body', index).find("#bbb");
//监听提交
iframeWindow.layui.form.on('submit(aaa)', function(data){
var field = data.field; //获取提交的字段
//提交 Ajax 成功后,静态更新表格中的数据
$.post("../demo1/student/add",field,function(result){
if(result.code==0){
layer.msg("添加成功");
table.reload('testReload'); //数据刷新
layer.close(index); //关闭弹层
}else if(result.code==2){
layer.msg("该卡号已有人使用");
}else{
layer.msg("添加失败");
}
},"json")
});
//触发submit按钮的点击方法
submit.trigger('click');
}
});
break;
case "btn1":
//执行实例
var uploadInst = upload.render({
elem: '#btn1' //绑定元素
,accept:"file"
,url: '../demo1/student/upload' //上传接口
,done: function(res){
//上传完毕回调
layer.msg("上传成功");
}
,error: function(){
//请求异常回调
layer.msg("导入数据不匹配,请检查");
}
});
break;
case "btn2":
layer.confirm('是否要导出?', function(index){
location.href="demo1/student/export";
layer.close(index);
});
break;
}
});
注:导入导出工具类见主页另一篇博文