工具类-Excel解析-EasyExcel最简读写

优缺点

  • 优点:易于上手,满足绝大多数日常所需
  • 缺点:无法快速对指定的单元格内容进行修改,精细处理还是推荐使用poi

依赖

<dependency>
	<groupId>com.alibabagroupId>
	<artifactId>easyexcelartifactId>
	<version>2.2.7version>
dependency>

实体类

public class ExcelData {
    @ExcelProperty("name")
    private String name;
    @ExcelProperty("nation")
    @ExcelIgnore
    private String nation;
    @ExcelProperty("中文测试")
    private String huzhaohao;
}

读写代码

public class TestExcel {
    public static void main(String[] args) throws Exception {
		
        /**
         * 基础的读写
         * 测试一下模板页的写法
         *
         * 无法指定单元格
         */
        List<ExcelData> tmpList = easyReadExcel();
        for (ExcelData excelData : tmpList){
            System.out.println(excelData);
        }

        writeExcel(tmpList);

        templateWrite();
    }

    public static void templateWrite() {
        String templateFileName = "demo.xls";
        String fileName = "demoOut.xls";
        List<ExcelData> tmpList = new ArrayList<>();
        for(int i = 0; i < 10; i++){
            ExcelData e = new ExcelData();
            e.setName("name" + i);
            e.setHuzhaohao("中文" + i);
            tmpList.add(e);
        }
        EasyExcel.write(fileName, ExcelData.class).withTemplate(templateFileName).sheet().doWrite(tmpList);
    }

    private static List<ExcelData> easyReadExcel() throws Exception{
        String fileName = "excelInput.xls";
        // 指定读用哪个class去读,然后读取第一个sheet(默认第一个,可传下标改变sheet页) 同步读取会自动finish
        List<ExcelData> tmpList = EasyExcel.read(fileName )
                .head(ExcelData.class).sheet().doReadSync();
        return tmpList;
    }

    // 导出报表
    private static void writeExcel(List<ExcelData> list) throws Exception{
        String fileName = "excelOutput.xlsx";
        EasyExcel.write(fileName, ExcelData.class).sheet("导出列表").doWrite(list);
    }
}

参考

官方文档

你可能感兴趣的:(java,开发语言)