30 使用easyExcel依赖生成Excel

30.1 导入依赖

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

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.16.12</version>
    </dependency>

30.2 创建一个类

        在类上加注解,@ExcelProperty,注解中value属性是列名,index属性是第几列。

package jiang.com;

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    @ExcelProperty(value = "姓名",index = 0)
    private String name;
    @ExcelProperty(value = "年龄",index = 1)
    private Integer age;
}

30.3 创建数据,使用EasyExcel的write方法完成excel创建

        首先,需要创建一个泛型为Student的集合,存放多个Student对象,一个对象相当于excel表格的其中一行。然后,调用EasyExcel的write方法,需要填写excel生成的路径(需要写到生成的excel文件名)以及Student类的反射。接着,使用sheet方法,传入表格的sheet名称。最后,使用doWrite方法,把集合写到excel中。

package jiang.com;

import com.alibaba.excel.EasyExcel;

import java.util.Arrays;
import java.util.List;

public class Demo1 {
    public static void main(String[] args) {
        // excel数据
        List<Student> list = Arrays.asList(
                                            new Student("张三1",30),
                                            new Student("张三2",31),
                                            new Student("张三3",32),
                                            new Student("张三4",34),
                                            new Student("张三5",35)
                                          );

        EasyExcel.write("2.xlsx",Student.class).sheet("学生").doWrite(list);
    }
}

猜你喜欢

转载自blog.csdn.net/no996yes885/article/details/132117642
30
今日推荐