點擊上方藍色字體,選擇「標星公眾號」
優質文章,第一時間送達
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。寫的不好,僅供參考。
版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處連結和本聲明。
本文連結:
https://blog.csdn.net/aa821198112/article/details/110733675
粉絲福利:實戰springboot+CAS單點登錄系統視頻教程免費領取
👇👇👇
感謝點讚支持下哈