官方文档
https://www.yuque.com/easyexcel/doc/easyexcel
先导入阿里EasyExcel的maven
<dependency>
<groupId>com.alibabagroupId>
<artifactId>easyexcelartifactId>
<version>2.2.6version>
dependency>
导入工具类
//参数说明
private final static String fileName1 = "D:\\" + System.currentTimeMillis() + ".xlsx";
public static void easyUtil(List<String> heads,String head,List<Map<String, Object>> list){
//设置表头和标题
List<List<String>> hs = new ArrayList<>();
for (String s : heads) {
hs.add(Arrays.asList(head,s));
}
Collection<Object> values;
List<List<Object>> list2 = new ArrayList<>();
//取出map的值,转换为list
for (int i = 0; i < list.size(); i++) {
List<Object> objects = new ArrayList<>();
values = list.get(i).values();
for (Object value : values) {
objects.add(value.toString());
}
list2.add(objects);
}
//核心代码
EasyExcel.write(fileName1).head(hs).sheet("模板(sheet名字)").doWrite(list2);
}
解析:EasyExcel.write(fileName1).head(hs).sheet(“模板(sheet名字)”).doWrite(list2);
write(fileName1)文件下载到的地方,
.head(hs)设置文件头
sheet(“模板(sheet名字)”) 设置表名
doWrite(list2); 需要写入的数据
public static void main(String[] args) {
List<String> heads = new ArrayList<>(); //表头信息
heads.add("银行名称");
heads.add("期间新增项目");
heads.add("期间新增担保总额");
heads.add("期间新增解保项目数");
heads.add("期间新增解保金额");
heads.add("在保项目数");
heads.add("在保余额");
heads.add("银行利率");
String head="惠农通数据表"; //主表头
List<Map<String, Object>> list = new ArrayList<>();
Map<String,Object> test = new LinkedHashMap<>(); //手动添加测试数据(可根据需要从数据库查询)
test.put("t1", 1);
test.put("t2", 2);
test.put("t3", 3);
test.put("t4", 4);
test.put("t5", 5);
test.put("t6", 6);
test.put("t7", 7);
test.put("t8", 8);
list.add(test);
Map<String,Object> test2 = new LinkedHashMap<>();
test.put("t1", 1);
test.put("t2", 2);
test.put("t3", 3);
test.put("t4", 4);
test.put("t5", 5);
test.put("t6", 6);
test.put("t7", 7);
test.put("t8", 8);
list.add(test2);
easyUtil(heads,head,list);
}
/**
*
* @param response
* @param heads 表头
* @param head 标题
* @param list 数据
* @return
* @throws IOException
*/
public static void easyUtil1(HttpServletResponse response,List<String> heads, String head, List<List<Object>> list) throws IOException {
//整合表头和标题
List<List<String>> hs = new ArrayList<>();
for (String s : heads) {
hs.add(Arrays.asList(head,s));
}
//设置表名
String fileName = new String((new SimpleDateFormat("yyyy-MM-dd").format(new Date())).getBytes(), "UTF-8");
//设置字符编码
response.setCharacterEncoding("utf-8");
//设置内容类型
response.setContentType("application/vnd.ms-excel");
//设置标题
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "utf-8"));
//核心代码
EasyExcel.write(response.getOutputStream()).head(hs).sheet("员工考勤").doWrite(list);
}
主要的就是工具类里的一行核心代码,其他的都很灵活.