easyexcel导出excel模板
pom文件添加jar依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.4</version>
</dependency>
导出excle
@GetMapping("export")
public void export(CivilizedLuckyDrawQuery query, HttpServletResponse response) {
DataResult<DrawVO> luckyDrawVODataResult = luckyDrawService.queryCivilizedList(query);
List<DrawVO> data = luckyDrawVODataResult.getData();
try {
String fileName = "excel命名_"+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
String sheetName = "sheet命名";
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
EasyExcel.write(response.getOutputStream(), CivilizedLuckyDrawVO.class).sheet(sheetName).doWrite(data);
} catch (IOException e) {
log.error("导出异常,e: {}", e);
}
}
导入excel
/**
* 解析excel取得数据
*
* @param tempFile
* @param suffix_flex
* @return
*/
public List<List<String>> getDatasByDealExcel(File tempFile, String suffix_flex) {
InputStream in = null;
try {
in = new FileInputStream(tempFile);
ExcelListener listener = new ExcelListener();
ExcelTypeEnum type = suffix_flex.equals(".xls") ? ExcelTypeEnum.XLS : ExcelTypeEnum.XLSX;
ExcelReader excelReader = new ExcelReader(in, type, null, listener);
excelReader.read();
//线面的获取也是正确的
//Sheet sheet = new Sheet(1, 1);
// List<Object> list = EasyExcelFactory.read(in, sheet);
List<List<String>> datas = listener.getDatas();
return datas;
} catch (Exception e) {
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
log.error("excel文件读取失败, 失败原因:{}", e);
}
}
return null;
}
ExcelListener代码展示;
@Component
public class ExcelListener extends AnalysisEventListener {
public List<List<String>> datas = new ArrayList<>();
@Override
public void invoke(Object o, AnalysisContext analysisContext) {
List<String> stringList= (List<String>) o;
System.out.println("当前sheet"+analysisContext.getCurrentSheet().getSheetNo()+ " 当前行:" + analysisContext.getCurrentRowNum()
+ " data:" + stringList.get(0));
datas.add(stringList);//数据存储到list,供批量处理,或后续自己业务逻辑处理。
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
public List<List<String>> getDatas() { return datas; }
public void setDatas(List<List<String>> datas) { this.datas = datas; }
}