参考 关于Easyexcel | Easy Excel
一、引入 pom.xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.10</version>
</dependency>
二、自定义模版
![](https://i-blog.csdnimg.cn/blog_migrate/4545819d8244ecc03fc211bdc09f7a3e.png)
三、测试示例
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import lombok.Data;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ExcelUtil {
public static void main(String[] args) {
// 模板文件路径
String tempFilePath = "/Users/sunny/templates/exportExcelTemplate.xlsx";
// 导出目标文件
String excelFileName = "/Users/sunny/templates/测试导出Excel.xlsx";
// 根据模板文件生成目标文件
ExcelWriter excelWriter = EasyExcel
.write(excelFileName)
.withTemplate(tempFilePath)
.build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
// 测试数据
List<UserTest> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
UserTest userTest = new UserTest();
userTest.setName("测试" + i);
userTest.setAge(25 + i);
userTest.setAddress("北京" + i);
list.add(userTest);
}
// 第一种
Map<String, List<?>> map = new HashMap<>();
map.put("data", list);
map.forEach((k, v) -> excelWriter.fill(new FillWrapper(k, v), writeSheet));
// 第二种
// excelWriter.fill(new FillWrapper("data", list), writeSheet);
excelWriter.finish();
}
}
@Data
class UserTest {
private String name;
private Integer age;
private String address;
}
四、导出结果
![](https://i-blog.csdnimg.cn/blog_migrate/a4df9d036e690cb0f0db37ee342da6fb.png)