欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

easyExcel使用demo

程序员文章站 2024-03-21 13:23:22
...

写入数据

 //写入单个sheet
    public static void writeData(List<DemoData> dataList){
        for (int i = 0; i < 3; i++) {
            EasyExcel.write(writeFileName).head(getHead()).sheet().doWrite(dataList);
        }

    }

    //写入多个sheet
    public static void writeMultiSheetData(List<DemoData> dataList){
        ExcelWriter multiSheetWriter = EasyExcel.write(writeFileName).build();
        for (int i = 0; i < 3; i++) {
            WriteSheet writeSheet = EasyExcel.writerSheet(i).head(getHead()).build();
            multiSheetWriter.write(dataList,writeSheet);
        }
        //一定要finish 要不然数据写不进去
        multiSheetWriter.finish();
    }
    private static List<List<String>> getHead(){
        List<List<String>> list = new ArrayList<List<String>>();
        List<String> head0 = new ArrayList<String>();
        head0.add("字符串" + System.currentTimeMillis());
        List<String> head1 = new ArrayList<String>();
        head1.add("数字" + System.currentTimeMillis());
        List<String> head2 = new ArrayList<String>();
        head2.add("日期" + System.currentTimeMillis());
        List<String> head3 = new ArrayList<String>();
        head3.add("名字" + System.currentTimeMillis());
        list.add(head0);
        list.add(head1);
        list.add(head2);
        list.add(head3);
        return list;
    }
读入数据
//Listener读取
public static void complexHeaderRead() {
    // 这里 需要指定读用哪个class去读,然后读取第一个sheet
    EasyExcel.read(readFileName, DemoData.class, new DemoDataListener()).sheet()
            // 这里可以设置1,因为头就是一行。如果多行头,可以设置其他值。不传入默认1行
            .headRowNumber(0).doRead();
}

//同步返回数据
public static List<DemoData> readSync() {
    // 这里 需要指定读用哪个class去读,然后读取第一个sheet
    List<DemoData> objects = EasyExcel.read(readFileName).headRowNumber(0)
            .head(DemoData.class).sheet().doReadSync();
    objects.forEach(System.out::println);
    return objects;
}