引言
EasyExcel 是阿里巴巴开源的一个基于Java的、简单易用的Excel操作工具,它可以帮助我们快速实现Excel文件的读写操作。相比于传统的 Apache POI,EasyExcel 具有内存占用低、API简单、性能优异等优点。
1、添加依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.1</version>
</dependency>
2、创建数据,这里以学生信息为模型
package com.tledu.export;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
@ExcelProperty("姓名")
private String name;
@ExcelProperty("年龄")
private int age;
@ExcelProperty("分数")
private double score;
}
@ExcelProperty
注解用于指定 Excel 表头名称。
类中的字段对应 Excel 文件中的列。
3.编写最简单的导出逻辑
package com.tledu.export;
import com.alibaba.excel.EasyExcel;
import java.util.ArrayList;
import java.util.List;
public class ExcelExport {
public static void main(String[] args) {
// 准备数据
List<Student> students = new ArrayList<Student>();
students.add(new Student("张三", 20, 80.5));
students.add(new Student("李四", 22, 90.0));
students.add(new Student("王五", 21, 83.5));
// 设置导出文件路径
String fileName = "D:\\EasyExcel\\students.xlsx";
// 使用EasyExcel导出数据
EasyExcel.write(fileName, Student.class)
.sheet("学生信息") // 设置sheet名称
.doWrite(students); // 写入数据
}
}
导出结果如下图
4.高级设置
通过 WriteTableStyle
来设置表头的字体、背景色等。
package com.tledu.export;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.IndexedColors;
import java.util.ArrayList;
import java.util.List;
public class ExcelExport {
public static void main(String[] args) {
// 准备数据
List<Student> students = new ArrayList<Student>();
students.add(new Student("张三", 20, 80.5));
students.add(new Student("李四", 22, 90.0));
students.add(new Student("王五", 21, 83.5));
// 设置表头样式
WriteCellStyle headCellStyle = new WriteCellStyle();
WriteFont headFont = new WriteFont();
headFont.setFontHeightInPoints((short) 14);
headFont.setBold(true);
headFont.setColor(IndexedColors.WHITE.getIndex());
headCellStyle.setWriteFont(headFont);
headCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
// 设置内容样式
WriteCellStyle contentCellStyle = new WriteCellStyle();
WriteFont contentFont = new WriteFont();
contentFont.setFontHeightInPoints((short) 12);
contentCellStyle.setWriteFont(contentFont);
// 创建样式策略
HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(headCellStyle, contentCellStyle);
// 设置导出文件路径
String fileName = "D:\\EasyExcel\\students.xlsx";
// 使用EasyExcel导出数据
EasyExcel.write(fileName, Student.class)
.registerWriteHandler(styleStrategy) // 样式策略
.sheet("学生信息") // 设置sheet名称
.doWrite(students); // 写入数据
}
}