EasyExcel看完肯定行
1.随便创建一个Excel表格
2.引入依赖
<dependencies><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.1.1</version></dependency><!-- 方便操作字段 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.26</version></dependency>
</dependencies>
3.读取Excel中的数据
public class ExcelTest {public static void main(String[] args) {List<ExcelData> list = new LinkedList<>();EasyExcel.read("testEasyexcel.xlsx").head(ExcelData.class)// 进行比对.sheet().registerReadListener(new AnalysisEventListener<ExcelData>() {@Overridepublic void invoke(ExcelData excelData, AnalysisContext analysisContext) {list.add(excelData);}@Overridepublic void doAfterAllAnalysed(AnalysisContext analysisContext) {}}).doRead();for (ExcelData excelData : list) {System.out.println(excelData);}}
}
4.写入Excel文件
4.1 创建与excel文件字段对应的实体类
@Data
public class ExcelData {// 成员变量和Excel字段映射@ExcelProperty("整数")private Integer id;@ExcelProperty("小数")private Double aDouble;@ExcelProperty("字符串")private String str;@ExcelProperty("姓名")private String name;
}
4.2 读取
public class StrData {public static void main(String[] args) {List<ExcelData> excelData = parseData();// 写入EasyExcel.write("test1.xlsx").excelType(ExcelTypeEnum.XLSX).sheet("sheet2").doWrite(excelData);}public static List<ExcelData> parseData(){LinkedList<ExcelData> list = new LinkedList<>();EasyExcel.read("testEasyexcel.xlsx").head(ExcelData.class)// 进行比对.sheet().registerReadListener(new AnalysisEventListener<ExcelData>() {@Overridepublic void invoke(ExcelData excelData, AnalysisContext analysisContext) {list.add(excelData);}@Overridepublic void doAfterAllAnalysed(AnalysisContext analysisContext) {}}).doRead();return list;}
}
5. 完整细节
public class test {public static void main(String[] args) {// 读取文件// 创建ExcelReaderBuilder实例ExcelReaderBuilder readerBuilder = EasyExcel.read();// 读取目标文件readerBuilder.file("testEasyexcel.xlsx");// 指定sheetreaderBuilder.sheet("sheet1");// 自动关闭输入流readerBuilder.autoCloseStream(true);// 设置Excel文件格式readerBuilder.excelType(ExcelTypeEnum.XLSX);// 注册监听器进行数据解析readerBuilder.registerReadListener(new AnalysisEventListener() {@Override // 将数据封装成Object 对象返回public void invoke(Object o, AnalysisContext analysisContext) {// 读完一行进行回调System.out.println(o);}@Overridepublic void doAfterAllAnalysed(AnalysisContext analysisContext) {// 读完全部进行回调 通知文件读取完毕System.out.println("读取完毕....");}});// 构建读取器ExcelReader reader = readerBuilder.build();// 读取数据reader.readAll();// 读取完毕reader.finish();}
}
完成…