首先需要明确:
Excel导入,需要先将Excel保存下来,再进行解析操作,最后将解析得到的数据插入到数据库中。
Excel导出,实际上是将数据查询出来,再将数据填充到逐渐创建出来的sheet表格中,最后使用下载的方式向页面传输。
这里会使用到本人自己封装的其他类,有兴趣的可以了解一下
ExcelUtils.java类:https://blog.csdn.net/weixin_43978412/article/details/108100422
FileUtils.java类:https://blog.csdn.net/weixin_43978412/article/details/108099849
GeneralUtils.java类:https://blog.csdn.net/weixin_43978412/article/details/108100100
创建User数据表
CREATE TABLE `user` (
`uid` varchar(50) NOT NULL COMMENT '用户id',
`username` varchar(50) NOT NULL COMMENT '用户名',
`password` varchar(50) NOT NULL COMMENT '密码',
`name` varchar(50) DEFAULT NULL COMMENT '姓名',
`start_year` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '入学年份',
`is_graduate` tinyint(1) DEFAULT NULL COMMENT '是否毕业',
`last_year_deposit` decimal(65,0) DEFAULT NULL COMMENT '去年存款',
`this_year_deposit` decimal(65,0) DEFAULT NULL COMMENT '今年存款',
`all_savings` decimal(65,0) DEFAULT NULL COMMENT '所有积蓄',
PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
<!-- 编译环境 -->
<build>
<plugins>
<!-- 设置项目的JDK编译版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- 启用maven内置tomcat7服务器 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
<!-- 任何SpringBoot的工程都要继承该父工程 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
</parent>
<!-- 加入springboot的web组件,版本随父工程的版本而定 -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 移除嵌入式tomcat插件 -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>Spring-boot-start-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- SpringBoot的test启动器依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- junit单元测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<!-- 导入SpringBoot整合mybatis的组件启动器 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<!-- 导入mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<!-- 导入servlet-api依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- 导入jsp-api依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!-- 对jsp的支持的依赖 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- 导入jstl标签库 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 处理JSON数据 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
<!-- log4j日志依赖 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.8.0-beta4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.8.0-beta4</version>
</dependency>
<!-- IO流 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- dom4j解析文档依赖 -->
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.3</version>
</dependency>
<!-- 封装map数据到javabean中 -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
<!-- 处理xls或xlsx格式的Excel表格导入导出的依赖 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<!-- 处理base64格式数据的依赖 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.13</version>
</dependency>
</dependencies>
省略。
import com.wnkj.entity.User;
import com.wnkj.service.UserService;
import com.wnkj.utils.ExcelUtils;
import com.wnkj.utils.FileUtils;
import com.wnkj.utils.GeneralUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
@RestController
@RequestMapping(value = "/file")
public class ExcelController {
@Autowired
private UserService userService;
private static Logger logger = Logger.getLogger(ExcelController.class);
/**
* 导入excel
* @param request
* @return
* @throws Exception
*/
@PostMapping(value = "/importExcel")
@ResponseBody
public String importExcel(HttpServletRequest request) throws Exception {
logger.info("开始解析Excel");
Map<String, Object> updateFileReturnMap = FileUtils.uploadFile(request);
String excelFilePath = (String) updateFileReturnMap.get("excelFile");
if (GeneralUtils.isEmpty(excelFilePath)) {
throw new RuntimeException("错误操作:没有选择上传文件");
}
int sheetNum = Integer.parseInt((String) updateFileReturnMap.get("sheetNum"));
logger.info("sheetNum = " + sheetNum);
int startRow = Integer.parseInt((String) updateFileReturnMap.get("startRow"));
logger.info("startRow = " + startRow);
int startCol = Integer.parseInt((String) updateFileReturnMap.get("startCol"));
logger.info("startCol = " + startCol);
String realPath = request.getServletContext().getRealPath("/static/" + excelFilePath);
logger.info("realPath = " + realPath);
List<Map<String, Object>> allUserMapList = new ArrayList<>();
List<List<Map<String, Object>>> lists = ExcelUtils.importExcel(realPath, startRow, startCol, sheetNum);
logger.info("mapList的长度 = " + lists.size());
for (List<Map<String, Object>> list : lists) {
logger.info("list的长度 = " + list.size());
for (int i = 1; i < list.size(); i++) {
Map<String, Object> dataMap = list.get(i);
Set<Map.Entry<String, Object>> set = dataMap.entrySet();
Map<String, Object> userMap = new HashMap<>();
userMap.put("uid", GeneralUtils.get32UUID());
for (Map.Entry<String, Object> entry : set) {
String key = entry.getKey();
logger.info("当前操作的是第" + (i + 1) + "行中的key = " + key);
Object value = entry.getValue();
String num = key.replace("Row" + (i + 1) + "-Col", "");
switch(num) {
case "1":
logger.info("num = " + num + " username = " + value);
userMap.put("username", value);
break;
case "2":
logger.info("num = " + num + " password = " + value);
userMap.put("password", value);
break;
case "3":
logger.info("num = " + num + " name = " + value);
userMap.put("name", value);
break;
case "4":
logger.info("num = " + num + " start_year = " + value);
userMap.put("start_year", value);
break;
case "5":
logger.info("num = " + num + " is_graduate = " + value);
userMap.put("is_graduate", Boolean.valueOf((String) value));
break;
case "6":
logger.info("num = " + num + " last_year_deposit = " + value);
userMap.put("last_year_deposit", value);
break;
case "7":
logger.info("num = " + num + " this_year_deposit = " + value);
userMap.put("this_year_deposit", value);
break;
case "8":
logger.info("num = " + num + " all_savings = " + value);
userMap.put("all_savings", value);
break;
}
}
allUserMapList.add(userMap);
}
System.out.println("allUserMapList = " + allUserMapList.size());
for (Map<String, Object> map : allUserMapList) {
System.out.println(map);
}
userService.batchAddUserMap(allUserMapList);
}
logger.info("结束解析Excel");
return "success";
}
/**
* 导出excel
* @param request
* @param response
* @throws Exception
*/
@GetMapping(value = "/exportExcel")
public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
String fileName = UUID.randomUUID().toString()
.replace("-", "").toUpperCase() + ExcelUtils.EXTENSION_NAME;
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
String title = "";
String[] rowName = new String[]{
"序号","用户编号","用户名","用户密码","用户姓名",
"入学年份","是否毕业","去年存款","今年存款","所有积蓄"
};
List<User> userList = userService.listAll();
List<Object[]> dataList = new ArrayList<>();
for (int i = 0; i < userList.size(); i++) {
User user = userList.get(i);
Object[] objArr = new Object[]{
i + 1,
user.getUid(),
user.getUsername(),
user.getPassword(),
user.getName(),
user.getStart_year(),
user.isIs_graduate(),
user.getLast_year_deposit(),
user.getThis_year_deposit(),
user.getAll_savings()
};
dataList.add(objArr);
}
OutputStream output = response.getOutputStream();
ExcelUtils.exportExcel(title, rowName, dataList, output);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>">
<meta charset="UTF-8">
<title>Show</title>
</head>
<body>
<form action="<%=basePath%>file/importExcel" method="POST" enctype="multipart/form-data">
解析表格的编号(从1开始):<input type="number" name="sheetNum" /><br/>
开始解析的行数(从1开始):<input type="number" name="startRow" /><br/>
开始解析的列数(从1开始):<input type="number" name="startCol" /><br/>
选择Excel文件:<input type="file" name="excelFile" /><br/>
<input type="submit" value="上传Excel">
</form>
<a href="<%=basePath%>file/exportExcel">到处用户数据到excel</a>
</body>
</html>
数据库User数据表没有数据:
启动项目,访问页面
导入的excel如下
导入之后,success表示成功
查看控制台:
查看数据库:
在jsp页面中点击导出用户信息
查看导出来的Excel表格
至此,Excel导入导出案例完成。