Hutool官网
Hutool-poi 是针对 Apache POI 的封装,因此需要用户自行引入 POI 库,Hutool 默认不引入。到目前为止,Hutool-poi 支持:
- Excel 文件(xls、xlsx)的读取(ExcelReader)
- Excel 文件(xls、xlsx)的写出(ExcelWriter)
引入 Hutool 的依赖或者 Jar 包,分别引入 POI 和 Hutool 的依赖。
1 2 3 4 5 6 7 8 9 10 11
| <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.3.8</version> </dependency>
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency>
|
Hutool 提供的类有:
- ExcelUtil Excel 工具类,读取的快捷方法都被封装于此。
- ExcelReader Excel 读取器,Excel 读取的封装,可以直接构造后使用。
- ExcelWriter Excel 生成并写出器,Excel 写出的封装(写出到流或者文件),可以直接构造后使用。
使用 Hutool 进行对 Excel 文件读取的时候,只需要一行代码,代码示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.hutool.demo;
import cn.hutool.core.io.FileUtil; import cn.hutool.poi.excel.ExcelReader; import cn.hutool.poi.excel.ExcelUtil;
import java.util.List; import java.util.Map;
public class ReadExcel {
public static void main(String[] args) { ExcelReader reader = ExcelUtil.getReader(FileUtil.file("/Users/apple/JavaProject/operation-excel/excel2007.xlsx")); List<Map<String, Object>> maps = reader.readAll(); System.out.println(maps.toString()); } }
|
执行结果:

Hutool 将 Excel 写出封装为 ExcelWriter,原理为包装了 Workbook 对象,每次调用 merge(合并单元格)或者 write(写出数据)方法后只是将数据写入到 Workbook,并不写出文件,只有调用 flush 或者 close 方法后才会真正写出文件。
由于机制原因,在写出结束后需要关闭 ExcelWriter 对象,调用 close 方法即可关闭,此时才会释放 Workbook 对象资源,否则带有数据的 Workbook 一直会常驻内存。
代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| package com.hutool.demo;
import cn.hutool.poi.excel.ExcelUtil; import cn.hutool.poi.excel.ExcelWriter; import com.hutool.entity.User;
import java.util.ArrayList; import java.util.Date; import java.util.List;
public class WriteExcel {
public static void main(String[] args) { ExcelWriter writer = ExcelUtil.getWriter("/Users/apple/JavaProject/operation-excel/HutoolWrite.xlsx"); writer.addHeaderAlias("userName", "姓名"); writer.addHeaderAlias("sex", "性别"); writer.addHeaderAlias("age", "年龄"); writer.addHeaderAlias("date", "日期"); List<User> user = new ArrayList<User>(); user.add(User.builder().userName("王晓霞").sex("女").date(new Date()).age(18).build()); writer.write(user, true); writer.close(); } }
|
打开Excel:
