66套java从入门到精通实战课程分享
前言实际工作中可能会用到Excel的导入和导出功能,Java操作Excel的方式有很多种,这里简单介绍一下如何使用EasyPoi来操作Excel。简单的做个笔记,防止自己忘记。
EasyPoi文档:http://easypoi.mydoc.io/
项目地址:https://gitee.com/lihongmin5211/springboot_easypoi
准备工作环境:
SpringBoot2.4.0、jdk8、Mysql5.7
表结构:
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL COMMENT '主键,非递增',
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '姓名',
`photo` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '照片',
`address` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '地址',
`birthday` datetime(0) DEFAULT NULL COMMENT '出生日期',
`tel` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '电话',
`sex` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '性别',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
Excel:
创建一个SpringBoot项目
过程这里就不细说了
pom.xml文件:
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<!-- easypoi相关的jar包 -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.2.0</version>
</dependency>
<!-- freemarker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
application.yml:
server:
port: 9001
spring:
freemarker:
suffix: .ftl
cache: false
charset: UTF-8
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8
username: root
password: *****
web:
resources:
static-locations: classpath:/static/
mybatis:
mapper-locations: classpath:/mapper/*.xml
type-aliases-package: com.lhm.entity
upload.dir: E:\java\study\springboot_easypoi\src\main\resources\static\imgs\
页面准备:
templates目录下新建一个studentList.ftl(这里用的是layui)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学生列表</title>
<link rel="stylesheet" href="/layui/css/layui.css">
</head>
<body>
<style>
//设置table的行高为自动适应
.layui-table-cell {
display: table-cell;
vertical-align: middle;
}
</style>
<div>
<button type="button" class="layui-btn" id="upload"><i class="layui-icon"></i>导入Excel</button>
</div>
<div>
<table class="layui-hide" id="studentTable"></table>
</div>
<div>
<button type="button" class="layui-btn layui-btn-warm" onclick="exportExcel()">导出Excel</button>
</div>
<script src="/layui/layui.js"></script>
<script src="/layui/layui.all.js"></script>
<script>
function exportExcel() {
location.href = "/export";
}
layui.use('upload', function () {
var $ = layui.jquery;
var upload = layui.upload;
//指定允许上传的文件类型
upload.render({
elem: '#upload'
, url: '/upload' //改成您自己的上传接口
, accept: 'file' //普通文件
, exts: 'xls|xlsx'
, done: function (res) {
layer.msg(res.message);
location.href = "/index";
}
});
});
layui.use('table', function () {
var table = layui.table;
table.render({
elem: '#studentTable'
, url: '/findAll'
, cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
, cols: [[
{field: 'id', title: 'ID', sort: true, align: 'center'}
, {field: 'name', title: '姓名', align: 'center'} //width 支持:数字、百分比和不填写。你还可以通过 minWidth 参数局部定义当前单元格的最小宽度,layui 2.2.1 新增
, {field: 'photo', title: '头像', align: 'center', templet: "#imgtmp"}
, {field: 'tel', title: '电话', align: 'center'}
, {field: 'sex', title: '性别', align: 'center'}
, {field: 'address', title: '地址', align: 'center'}
, {
field: 'birthday',
title: '出生日期',
align: 'center',
templet: "<div>{{layui.util.toDateString(d.birthday, 'yyyy-MM-dd')}}</div>"
}
]]
});
});
</script>
<script type="text/html" id="imgtmp">
<img src="{{'imgs/'+d.photo}}" style="width: 80px;height: 80px"/>
</script>
</body>
</html>
新建个StudentController里面写个跳转方法
@RequestMapping({"/", "/index"})
public String stuList() {
return "studentList";
}
效果:
正式开发新建一个entity包,包下新建一个实体类Student
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {
@Excel(name = "编号")
private Integer id;
/**
* width和height是导出是图片的宽度和高度
* type:类型,2代表图片
* savePath:保存的路径(右击保存图片的文件夹,选Copy Path就行,这里是存在static下的imgs中)
*/
@Excel(name = "头像",width = 12.0,height = 12.0,type = 2,savePath = "E:\\java\\study\\springboot_easypoi\\src\\main\\resources\\static\\imgs")
private String photo;
@Excel(name = "姓名")
private String name;
@Excel(name = "电话",width = 20.0)
private String tel;
@Excel(name = "性别")
private String sex;
@Excel(name = "地址",width = 30.0)
private String address;
@Excel(name = "出生日期",format = "yyyy/MM/dd",width = 15.0)
private Date birthday;
}
StudentController代码:
@Controller
@Slf4j
public class StudentController {
@Autowired
StudentService studentService;
@Value("${upload.dir}")
private String filePath;
@RequestMapping({"/", "/index"})
public String stuList() {
return "studentList";
}
/**
* 导入Excel
* @param file
* @return
*/
@RequestMapping("/upload")
@ResponseBody
public Result upload(MultipartFile file) {
try {
String originalFilename = file.getOriginalFilename();
log.info(originalFilename);
ImportParams params = new ImportParams();
//标题行,如果没有就不填,否则导入时数据会变成null
params.setTitleRows(1);
//头行,例如:姓名、地址、联系方式 这些字段所占的行,占几行就填几
params.setHeadRows(1);
//执行导入方法,返回的是一个集合(将Excel中的数据变成了pojo组成的集合)
List<Student> students = ExcelImportUtil.importExcel(file.getInputStream(), Student.class, params);
//调用getImgName方法获取图片名
List<Student> list = getImgName(students);
students.forEach(System.out::println);
//调用方法将数据保存到数据库
studentService.saveBatch(list);
return Result.success("上传成功", originalFilename);
} catch (Exception e) {
e.printStackTrace();
return Result.fail("上传失败");
}
}
/**
* 导出excel
* @param response
* @throws IOException
*/
@RequestMapping("/export")
public void exportExcel(HttpServletResponse response) throws IOException {
//查询出要导出的数据
List<Student> students = studentService.findAll();
//修改图片的地址(改成实际的路径)
students.forEach(student -> {
student.setPhoto(filePath + student.getPhoto());
});
//生成Excel
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("学生信息列表", "学生信息"), Student.class, students);
response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("学生信息.xls", "UTF-8"));
ServletOutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.close();
workbook.close();
}
/**
* 前端获取信息用于展示,这里不做分页了
* @return
*/
@RequestMapping("/findAll")
@ResponseBody
public Map<String, Object> findAll() {
List<Student> all = studentService.findAll();
Map<String, Object> map = new HashMap<>();
map.put("code", 0);
map.put("msg", "获取成功");
map.put("count", all.size());
map.put("data", all);
return map;
}
/**
* 获取图片名
* @param students
* @return
*/
public List<Student> getImgName(List<Student> students) {
students.forEach(student -> {
String fileName = student.getPhoto().substring(student.getPhoto().lastIndexOf("\\") + 1);
student.setPhoto(fileName);
});
return students;
}
}
在写一个配置类:(这玩意不配置都不行,不配置上传后图片显示不出来,需要重启服务器才行)
@Configuration
public class MyImgConfig implements WebMvcConfigurer {
@Value("${upload.dir}")
private String filePath;
/**
* 不配置这个的话上传成功后需要重启服务器才能访问到图片
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/imgs/**").addResourceLocations("file:"+filePath);
}
}
mapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.lhm.mapper.StudentMapper">
<insert id="savtBatch" parameterType="java.util.List">
insert into student(id,name,photo,address,birthday,tel,sex) values
<foreach collection="list" item="student" index="index" separator=",">
(#{student.id},#{student.name},#{student.photo},#{student.address},#{student.birthday},#{student.tel},#{student.sex})
</foreach>
</insert>
<select id="findAll" resultType="com.lhm.entity.Student">
select * from student
</select>
</mapper>
测试
导入:
导出:
结论
实现了利用EasyPOI对Excel的简单操作(导入/导出),项目源码码云上有,项目地址:https://gitee.com/lihongmin5211/springboot_easypoi。写的不好,仅供参考。