引入依赖
easyExcel依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.3</version>
</dependency>
只引入easyexcel依赖运行可能会报错,就还需要引入poi的相关依赖,注意easyExcel和poi的版本兼容问题
<!--POI start-->
<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-scratchpad</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
<!--POI end-->
编写工具类
/**
* @Description: easyExcel工具类
* @Author along
* @Date 2022/9/16 17:56
*/
public class EasyExcelUtils {
private static final Logger log = LoggerFactory.getLogger(EasyExcelUtils.class);
/**
* 单sheet页导出
*
* @param response HttpServletResponse对象
* @param excelName 导出文件名
* @param sheetName sheet名称
* @param clazz 类
* @param data 数据
* @throws Exception
*/
public static void export(HttpServletResponse response, String excelName, String sheetName, Class clazz, List data) throws Exception {
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码
excelName = URLEncoder.encode(excelName, "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + excelName + ExcelTypeEnum.XLSX.getValue());
EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(data);
} catch (Exception e) {
log.error("", e);
}
}
/**
* 多sheet页导出
*
* @param response
* @param excelName excel名称
* @param sheetMessages sheet信息列表
*/
public static void exportMoreSheet(HttpServletResponse response, String excelName, List<SheetMessage> sheetMessages) {
ExcelWriter excelWriter = null;
try {
// 设置响应头信息
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
excelName = URLEncoder.encode(excelName, "UTF-8"); // 这里URLEncoder.encode可以防止中文乱码
response.setHeader("Content-disposition", "attachment;filename=" + excelName + ExcelTypeEnum.XLSX.getValue());
// 创建ExcelWriter对象
excelWriter = EasyExcel.write(response.getOutputStream()).build();
AtomicInteger count = new AtomicInteger(); // 计数器变量
for (EasyExcelUtils.SheetMessage message : sheetMessages) {
WriteSheet sheet = EasyExcel.writerSheet(count.get(), message.getSheetName()).head(message.getClazz()).build();
// 写入Sheet数据
excelWriter.write(message.getData(), sheet);
count.getAndIncrement();
}
} catch (Exception e) {
log.error("", e);
} finally {
// 关闭ExcelWriter
if (excelWriter != null) {
excelWriter.finish();
}
}
}
@Data
@NoArgsConstructor // 自动生成无参构造方法
@AllArgsConstructor // 自动生成全参构造方法
public static class SheetMessage {
/**
* sheet页名称
*/
private String sheetName;
/**
* Class
*/
private Class<?> clazz;
/**
* 数据
*/
private List data;
}
}
应用
单sheet页excel导出
构建导出对象实体
/**
* @Description: excel导出对象
* @Author along
* @Date 2022/9/16 17:11
*/
@Data
public class Demo {
/**
* value:定义表头名称,下面是简单表头,复杂表头写法:value={"aaa","bbb"}
* index:定义位置,0代表第一列,不写就默认从上往下排序
*/
@ColumnWidth(20)
@ExcelProperty(value = "学号",index = 0)
private Long id;
@ColumnWidth(20)
@ExcelProperty(value = "名字",index = 1)
private String name;
@ColumnWidth(20)
@ExcelProperty(value = "性别",index = 2)
private String gender;
@ColumnWidth(20)
@ExcelProperty(value = "爱好",index = 3)
private String hobby;
}
导出逻辑代码,下面是伪代码,意思一下
// 获取数据源
List<Demo> list = demoDao.list();
// 填充导出对象ExportTaskObjectVo
List<ExportTaskObjectVo> exportVos = new ArrayList<>();
for (VTopicDialTestInternetTask e : list) {
ExportTaskObjectVo v = new ExportTaskObjectVo();
v.setCustomersNum(e.getCustomersNum());
v.setCustomersName(e.getCustomersName());
v.setLineId(e.getLineId());
v.setLineType(e.getLineType());
exportVos.add(v);
}
// 调用工具类导出Excel
EasyExcelUtils.export(response,
"demo", // 导出的excel文件的文件名
"sheet1", // excel第一个sheet的名称
ExportTaskObjectVo.class,
exportVos
);
完毕,单sheet页导出是开发中最常用的,有时候我们需要导出多sheet页的excel,如下:
多sheet页导出
// 获取数据源
List<Demo1> list1 = demoDao.list1();
List<Demo2> list2 = demoDao.list2();
List<Demo3> list3 = demoDao.list3();
List<Demo4> list4 = demoDao.list4();
List<EasyExcelUtils.SheetMessage> sheetMessages = new LinkedList<>();
sheetMessages.add(new EasyExcelUtils.SheetMessage("sheet1", Demo1.class, list1));
sheetMessages.add(new EasyExcelUtils.SheetMessage("sheet2", Demo2.class, list2));
sheetMessages.add(new EasyExcelUtils.SheetMessage("sheet3", Demo3.class, list3));
sheetMessages.add(new EasyExcelUtils.SheetMessage("sheet4", Demo4.class, list4));
String excelName = "output.xlsx"; // 导出文件名
EasyExcelUtils.exportMoreSheet(response, excelName, sheetMessages);
完事,导出就这样简单,基本一看就能用
导入Excel并解析
导入的excel模板如下:
根据模板Excel内容构建与之匹配的接收类
@Data
public class DemoExcelModel {
@ExcelProperty(value = "姓名", index = 0)
private String name;
@ExcelProperty(value = "爱好", index = 1)
private String hobby;
}
下面是Controller里的接收解析逻辑
@RestController
@RequestMapping("/demo")
@CrossOrigin
@Slf4j
public class DemoController {
@PostMapping("/parsing/excel")
public void excel2Object(@RequestParam("file") MultipartFile file) throws IOException {
log.info("接收并解析excel");
InputStream inputStream = file.getInputStream();
List<Object> excelModels = EasyExcel.read(inputStream)
.head(DemoExcelModel.class)
.sheet() // 设置sheet,默认读取第一个
.headRowNumber(1) // 设置标题所在行数
.doReadSync();
log.info("Excel解析完成:{}", excelModels);
// 解析完毕,下面想怎么处理这个数据就怎么处理
for (Object object : excelModels) {
// 强转
DemoExcelModel model = (DemoExcelModel) object;
// do something
}
}
}
完事