Java数据导出到Excel中并下载
使用的工具:Hutool
工具介绍:一个Java基础工具类,对文件、流、加密解密、转码、正则、线程、XML等JDK方法进行封装,组成各种Util工具类。关键在于,里面的所有方法你都可以用其它的来代替,都不是必须的。也没有集成其它的包,例如导出excel就需要引入poi的包,而hutool没有强制引入。
1,pom文件
2,service层
@Override
public byte[] downloadResult(PageQuery page, Date time, String keyword, String[] levelArr,
String[] typeArr, String[] substationArr, String[] equipmentArr) {
// TODO Auto-generated method stub
ExcelWriter writer = ExcelUtil.getWriter();
//标题和内容相当于k/v,
Map<String, String> map = MapUtil.newHashMap(true);
map.put("id", "告警序号");
map.put("savedTime", "存储时间");
writer.setHeaderAlias(map);
//查询的数据
List<Alarm> alarmlist = alarmMapper.getAlarmByPage(page, startTime, endTime, keyword, levelArr, typeArr, substationArr, equipmentArr);
for(int i=0;i<alarmlist.size();i++) {
ExportParam export = new ExportParam();
export.setId(alarmlist.get(i).getId());
//将date类型和转换成string
export.setSavedTime(DateUtil.formatDateTime(alarmlist.get(i).getSavedTime()));
export.setSource(alarmlist.get(i).getSource());
exports.add(export);
}
writer.write(exports);
ByteArrayOutputStream out = new ByteArrayOutputStream();
writer.flush(out);
// 关闭writer,释放内存
writer.close();
IOUtils.closeQuietly(out);
return out.toByteArray();
}
map里面放的是Excel中的表头和对应的字段、而后通过ExcelWriter对象writer.setHeaderAlias(map)把map放进去就行了。for循环将数据依次放入excel。
3,controller层
@GetMapping("/download")
public void download(HttpServletResponse response,PageQuery page ,Date time ,String keyword,String[] levelArr, String[] typeArr, String[] substationArr, String[] equipmentArr) throws Exception {
byte[] data = alarmService.downloadResult(pageDate, time, keyword, levelArr, typeArr, substationArr, equipmentArr);
String fileName = new DateTime().toString("yyyyMMddHHmm") + "告警数据" + ".xls";
response.setContentType("application/octet-stream; charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; fileName=" + fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
response.addHeader("Content-Length", "" + data.length);
IOUtils.write(data, response.getOutputStream());
}
需要注意的是,文件名不能有空格,例如yyyyMMddHHmm格式不能是yyyy-MM-dd HH-mm-ss
response.setContentType("application/octet-stream; charset=UTF-8");
对应的是xls,
想要导出格式为xlsx,则用response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
最后导出的数据: