简单的导出Excel步骤
一、maven导入依赖
<!-- EasyExcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.8</version>
</dependency>
二、创建导出的实体类
实体类需要加入 @ExcelIgnoreUnannotated 注解。
实体类中,每个属性对应导出excel中的一列,@ExcelProperty注解内的值为导出Excel中每一列的标题,@ContentRowHeight,@HeadRowHeight,@ColumnWidth分别对应内容行高,标题行高,列宽,大家可以自己调参数试试效果。
@Data
@ExcelIgnoreUnannotated
@ContentRowHeight(20)
@HeadRowHeight(20)
@ColumnWidth(25)
public class Student {
@ExcelProperty("姓名")
private String name;
@ExcelProperty("年龄")
private Integer age;
}
三、写导出方法
此处介绍如何在本地导出Excel文件。
首先写文件名和要导出的位置。这里我在resources目录下建立了excel文件夹,用于存放导出的Excel表。路径建议使用相对路径。
获取用于导出的List,这里添加了两条学生数据。
执行导出,Easy.write方法的第一个参数是输出流,第二个参数是刚才新建的实体类.class;.doWrite方法中参数为刚才添加了两条学生数据的List
@Test
public void exportStudentExcelTest(){
try{
// 1.写文件名和导出位置
String path = "src/main/resources/excel/";
String fileName = "学生列表.xlsx";
String name = path + fileName;
OutputStream outputStream = new FileOutputStream(name);
// 2.获取要导出的List
List<Student> list = new ArrayList<>();
list.add(new Student("李斯",18));
list.add(new Student("吕布",40));
// 3.EasyExcel导出
EasyExcel.write(outputStream,Student.class)
.sheet("学生列表")
.doWrite(list);
}catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("导出失败,请重试");
}
}
查看结果
文件保存在resources/excel目录中
打开可以看到文件中是我们刚才添加的数据