方法一:poi原生工具
1、引入依赖
//转换MultipartFile文件编译时用到
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.9</version>
<scope>compile</scope>
</dependency>
//主要的excel解析工具依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
2、简单代码示例
private void analyzeExcel() throws Exception {
//读取excel,excel路径
String excelPath = "/usr/local/hy/static/hy_resources/mid/notice.xlsx";
//poi工具使用代码
InputStream inputStream = null;
try {
inputStream = new FileInputStream(excelPath);
} catch (Exception e) {
log.info("公告excel文件读取失败!!!!");
}
//用HUtool ExcelUtil获取ExcelReader指定输入流和sheet
//设置表头对应字段
ExcelReader excelReader = ExcelUtil.getReader(inputStream);
excelReader.addHeaderAlias("公告类型", "contentType");
excelReader.addHeaderAlias("公告子类型", "attachType");
excelReader.addHeaderAlias("公告标题", "title");
excelReader.addHeaderAlias("公告日期", "noticeTime");
excelReader.addHeaderAlias("关联基金代码", "fundCodes");
excelReader.addHeaderAlias("公告路径(文件)", "filePath");
//读取数据
List<FundNoticeTransDTO> fundNoticeTransDTOS =
excelReader.readAll(FundNoticeTransDTO.class);
}
方法二:easyExcel工具
1、引入依赖
//转换MultipartFile文件编译时用到
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.9</version>
<scope>compile</scope>
</dependency>
//主要的excel解析工具依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
2、简单代码示例
private void analyzeExcel() throws Exception {
//读取excel,excel路径
String excelPath = "/usr/local/hy/static/hy_resources/mid/notice.xlsx";
//PageReadListener是excel读取监听事件,可以对读取的数据做一些验证处理之类的
//这里为了简单,写了个匿名类,实际用到时可以声明一个监听对象进行数据验证,处理
EasyExcel.read(excelPath, FundNoticeTransDTO.class, new
PageReadListener<FundNoticeTransDTO>(dataList -> {
//映射列表处理逻辑...
})).sheet().doRead();
}