好用的excl工具easyexcl

1.maven

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.6</version>
</dependency>


2.demodata
package com.demo.controller.excl;

import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

import java.util.Date;

@Data

public class DemoData {

    @ExcelProperty("字符串标题")

    private String string;

    @ExcelProperty("日期标题")

    private Date date;

    @ExcelProperty("数字标题")

    private Double doubleData;

    /**

     * 忽略这个字段

     */

    @ExcelIgnore

    private String ignore;

}
View Code
package com.demo.controller.excl;

import lombok.Data;


@Data
public class TestFileUtil {
    private   String path="D:\\log\\";
}
View Code
package com.demo.controller.excl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author :
 * @date :Created in 2021/5/24 20:13
 * @description:${description}
 * @modified By:
 * @version: $version$
 */
@Slf4j
public class WriteTest {
    /**
     * 最简单的写
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link DemoData}
     * <p>
     * 2. 直接写即可
     */
    public void simpleWrite() {
        // 写法1

        TestFileUtil testFileUtil=new TestFileUtil();
        String fileName =testFileUtil.getPath() + System.currentTimeMillis() + ".xlsx";
       log.info("fileName={}",fileName);
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());

        // 写法2
        fileName = testFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写
        ExcelWriter excelWriter = null;
        try {
            excelWriter = EasyExcel.write(fileName, DemoData.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
            excelWriter.write(data(), writeSheet);
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }


    private List<DemoData> data() {
        List<DemoData> list = new ArrayList<DemoData>();
        for (int i = 0; i < 10; i++) {
            DemoData data = new DemoData();
            data.setString("字符串" + i);
            data.setDate(new Date());
            data.setDoubleData(0.56);
            list.add(data);
        }
        return list;
    }
}
View Code

 

posted @ 2021-05-25 15:03  甜菜波波  阅读(118)  评论(0编辑  收藏  举报