poiAndEasyExcel学习(五)

2020-08-04 16:06:48 浏览数 (1)

EasyExcel操作

官方文档

导入依赖

代码语言:javascript复制
		// easyexcel
    // https://mvnrepository.com/artifact/com.alibaba/easyexcel
    compile group: 'com.alibaba', name: 'easyexcel', version: '2.2.6'

		// https://mvnrepository.com/artifact/com.alibaba/fastjson
		compile group: 'com.alibaba', name: 'fastjson', version: '1.2.72'

写入测试

写地址

创建对象

代码语言:javascript复制
package easyExcel;

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

import java.util.Date;

/**
 * @program: poiAndEasyExcel
 * @description:
 * @author: cuixy
 * @create: 2020-06-30 17:35
 **/
public class DemoData {

    @ExcelProperty("字符串标题")
    private String string;
    @ExcelProperty("日期标题")
    private Date date;
    @ExcelProperty("数字标题")
    private Double doubleData;
    /**
     * 忽略这个字段
     */
    @ExcelIgnore
    private String ignore;

    public String getString() {
        return string;
    }

    public void setString(String string) {
        this.string = string;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Double getDoubleData() {
        return doubleData;
    }

    public void setDoubleData(Double doubleData) {
        this.doubleData = doubleData;
    }

    public String getIgnore() {
        return ignore;
    }

    public void setIgnore(String ignore) {
        this.ignore = ignore;
    }
}

拿到实体类里的值

代码语言:javascript复制
 //当前项目的路径。
    static String PATH = "/Users/cuixiaoyan/biancheng/utils/Java/poiAndEasyExcel/easyExcel/";

    private List<DemoData> data() {
        java.util.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;
    }

将list写入Excel

代码语言:javascript复制
// 根据list 写入excel
    @Test
    public void simpleWrite() {
        // 写法1
        String fileName = PATH   "EasyTest.xlsx";
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        // write (fileName, 格式类)
        // sheet (表明)
        // doWrite (数据)
        EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());
    }

0 人点赞