1.读取excel
1.1创建监听器
public class ExcelListener extends AnalysisEventListener<Map<Integer, String>> {
protected Log log = LogFactory.getLog(this.getClass());
private final List<Map<Integer, String>> dataList = Collections.synchronizedList(new ArrayList<>());
@Override
public void invoke(Map<Integer, String> data, AnalysisContext context) {
dataList.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
log.info("所有数据解析完成!");
}
public List<Map<Integer, String>> getDataList() {
return dataList;
}
}
1.2读取数据
ExcelListener listener = new ExcelListener();
EasyExcel.read(filePath, listener).sheet(sheetNo).doRead();
List<Map<Integer, String>> dataList = listener.getDataList();
2.写EXCEL
2.1 excel头数据
List<List<String>> excelHeader = new ArrayList<>();
excelHeader.add(Collections.singletonList("标题1"));
excelHeader.add(Collections.singletonList("标题2"));
return excelHeader;
2.2 写入单sheet
// List<List<String>> dataList 类型
EasyExcel.write(dist).head(excelHeader).doWrite(dataList);
2.3 写入多sheet
try (ExcelWriter excelWriter = EasyExcel.write(dist).build()) {
ExcelWriterSheetBuilder userExcelSheet1 = new ExcelWriterSheetBuilder();
userExcelSheet1.head(excelHeader);
userExcelSheet1.sheetNo(0);
excelWriter.write(dataList1, userExcelSheet1.build());
ExcelWriterSheetBuilder userExcelSheet2 = new ExcelWriterSheetBuilder();
userExcelSheet2 .head(excelHeader);
userExcelSheet2 .sheetNo(1);
excelWriter.write(dataList2, userExcelSheet2 .build());
}