提交 addd0bdf 编写于 作者: W wenguang

Excel导入并读入数据库

上级 c738a1a6
package com.we.controller;
import java.net.URLEncoder;
import com.alibaba.excel.EasyExcel;
import com.we.pojo.Student;
import com.we.service.IStudentService;
import com.we.service.impl.StudentServiceImpl;
import com.we.util.UploadDataListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@Controller
public class ExcelController {
private String prefix = "/excelop";
@Autowired
private IStudentService studentService;
@Autowired
private StudentServiceImpl studentServiceImpl;
@GetMapping("/excel")
public String excel() {
return prefix + "/excel";
}
/**
* 导出Excel
*/
@RequestMapping("/exportExcel")
public String exportExcel() {
List stuList = studentService.selectStuList();
String path = "F:/Desktop/";
String fileName = path + "学生信息表格" + System.currentTimeMillis() + ".xlsx";
EasyExcel.write(fileName, Student.class).sheet("学生信息表格").doWrite(stuList);
return prefix + "/exportExcel";
}
/**
* 下载Excel
*
* @param response
*/
@RequestMapping("/downloadExcel")
public void downloadExcel(HttpServletResponse response) throws IOException {
List stuList = studentService.selectStuList();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码
String fileName = URLEncoder.encode("学生信息表下载", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), Student.class).sheet("学生信息").doWrite(stuList);
}
/**
* Excel导入
* @param file
* @return
* @throws IOException
*/
@PostMapping("/uploadExcel")
@ResponseBody
public String uploadExcel(@RequestParam("fileName")MultipartFile file) throws IOException {
EasyExcel.read(file.getInputStream(), Student.class, new UploadDataListener(studentServiceImpl)).sheet().doRead();
return "success";
}
}
......@@ -6,9 +6,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
......
......@@ -9,4 +9,6 @@ import java.util.List;
public interface StudentMapper {
public List<Student> selectStuList();
public int insertStuList(List<Student> list);
}
package com.we.pojo;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Data
@Getter
@Setter
@ToString
public class Student {
public class Student extends BaseRowModel {
@ExcelProperty(value = "学号", index = 0)
private String stuid;
@ExcelProperty(value = "班级", index = 1)
private String stuclass;
@ExcelProperty(value = "姓名", index = 2)
private String stuname;
@ExcelProperty(value = "年龄", index = 3)
private String stuage;
@ExcelProperty(value = "性别", index = 4)
private String stusex;
@ExcelProperty(value = "电话", index = 5)
private String stutel;
}
......@@ -7,4 +7,6 @@ import java.util.List;
public interface IStudentService {
public List<Student> selectStuList();
public int insertStuList(List<Student> list);
}
......@@ -18,4 +18,10 @@ public class StudentServiceImpl implements IStudentService {
public List<Student> selectStuList() {
return studentMapper.selectStuList();
}
@Override
public int insertStuList(List<Student> list) {
int flag = studentMapper.insertStuList(list);
return flag;
}
}
package com.we.util;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.we.pojo.Student;
import com.we.service.impl.StudentServiceImpl;
import java.util.ArrayList;
import java.util.List;
/**
* Excel读取监听
*/
public class UploadDataListener extends AnalysisEventListener<Student> {
// 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收
private static final int BATCH_COUNT = 5;
List<Student> list = new ArrayList<Student>();
private StudentServiceImpl studentServiceImpl;
public UploadDataListener() {
// 这里是demo,所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数
studentServiceImpl = new StudentServiceImpl();
}
/**
* 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
*
* @param studentServiceImpl
*/
public UploadDataListener(StudentServiceImpl studentServiceImpl) {
this.studentServiceImpl = studentServiceImpl;
}
@Override
public void invoke(Student data, AnalysisContext context) {
list.add(data);
// 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
if (list.size() >= BATCH_COUNT) {
saveData();
// 存储完成清理 list
list.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 这里也要保存数据,确保最后遗留的数据也存储到数据库
saveData();
}
/**
* 加上存储数据库
*/
private void saveData() {
studentServiceImpl.insertStuList(list);
}
}
......@@ -29,4 +29,13 @@
</where>
</select>
<insert id="insertStuList">
insert into student
(stuid, stuclass, stuname, stuage, stusex, stutel)
values
<foreach collection="list" item="stulist" separator=",">
(#{stulist.stuid}, #{stulist.stuclass}, #{stulist.stuname}, #{stulist.stuage}, #{stulist.stusex}, #{stulist.stutel})
</foreach>
</insert>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="true" /> <!-- 全局映射器启用缓存 -->
<setting name="useGeneratedKeys" value="true" /> <!-- 允许 JDBC 支持自动生成主键 -->
<setting name="defaultExecutorType" value="REUSE" /> <!-- 配置默认的执行器 -->
<setting name="logImpl" value="SLF4J" /> <!-- 指定 MyBatis 所用日志的具体实现 -->
<!-- <setting name="mapUnderscoreToCamelCase" value="true"/> 驼峰式命名 -->
</settings>
</configuration>
\ No newline at end of file
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>导入导出</title>
</head>
<body>
<a href="#" th:href="@{/exportExcel}">导出Excel</a><br/>
<a href="#" th:href="@{/downloadExcel}">下载Excel</a>
<form action="uploadExcel" method="post" enctype="multipart/form-data">
<input type="file" name="fileName"/>
<input type="submit"/>
</form>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>导出成功</title>
</head>
<body>
导出成功!
</body>
</html>
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册