<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel --> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.1.3</version> </dependency> <!--xls--> <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>
编写实体类
@Data public class DemoData { //设置excel表头名称 @ExcelProperty(value = "学生编号",index = 0) private Integer sno; @ExcelProperty(value = "学生姓名",index = 1) private String sname; }生成Excel
public class TestEasyExcelWrite { public static void main(String[] args) { //实现excel写的操作 //1 设置写入文件夹地址和excel文件名称 String filename = "C:\\Users\\aus\\write.xlsx"; // 2 调用easyexcel里面的方法实现写操作 // write方法两个参数:第一个参数文件路径名称,第二个参数实体类class EasyExcel.write(filename,DemoData.class).sheet("学生列表").doWrite(getData()); } //创建方法返回list集合 private static List<DemoData> getData() { List<DemoData> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { DemoData data = new DemoData(); data.setSno(i); data.setSname("lucy"+i); list.add(data); } return list; } }效果如下:
读取excel需要先写一个监听器继承AnalysisEventListener
public class ExcelListener extends AnalysisEventListener<DemoData> { //一行一行读取excel内容 @Override public void invoke(DemoData data, AnalysisContext analysisContext) { System.out.println("****"+data); } //读取表头内容 @Override public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) { System.out.println("表头:"+headMap); } //读取完成之后 @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { } }读取Excel
public class TestEasyExcelRead { public static void main(String[] args) { //实现excel读操作 String filename = "C:\\Users\\aus\\write.xlsx"; EasyExcel.read(filename,DemoData.class,new ExcelListener()).sheet().doRead(); } }效果如下:
以上为EasyExcel的用法。