public void ResultExport(Integer id, HttpServletRequest request, HttpServletResponse response) throws Exception {
PageResult<Info> info = null;
try {
//查询出需要导出的数据
info = resutService.resultExport(id);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = simpleDateFormat.format(new Date());
Map<String, Object> map=new HashMap<>(1);
map.put("results", info.getList());
//支持文件名中文
String filename = "导出结果(" + dateStr + ").xls";
//解决下载文件名称乱码
String header = request.getHeader("User-Agent").toUpperCase();
//IE浏览器
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
filename = URLEncoder.encode(filename, "utf-8");
//IE下载文件名空格变+号问题
filename = filename.replace("+", "%20");
} else {
//其他浏览器
filename = new String(filename.getBytes(), "ISO8859-1");
}
String templatePath = "template/resultExport.xls";//模版文件路径
response.setHeader("Content-Type", "application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
Map <String, Object> funcs = new HashMap <>(1);
funcs.put("util", LotteryController.class);
ExcelUtil.write(templatePath, response.getOutputStream(), map,funcs);
} catch (Exception e) {
logger.error("服务器处理异常", e);
throw new RuntimeException("服务器处理异常");
}
}
如果是浏览器不兼容的话记得在java代码中加入:
//解决下载文件名称乱码
String header = request.getHeader("User-Agent").toUpperCase();
//IE浏览器
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
filename = URLEncoder.encode(filename, "utf-8");
//IE下载文件名空格变+号问题
filename = filename.replace("+", "%20");
} else {
//其他浏览器
filename = new String(filename.getBytes(), "ISO8859-1");
}
ps:excel表中的字段必须要与实体类中的字段保持一致!