利用excel模板来导出excel文件, 十分方便
@RequestMapping(value = "/download/vin", method = RequestMethod.GET)
@ResponseBody
public ResBody exportExcel(HttpServletRequest request) {
String path = request.getSession().getServletContext().getRealPath("/download/");
List<Map<String,Object>> list= (List<Map<String, Object>>) testService.findAllVinData();
// 准备好要导出的数据
File file=null;
try {
file = ResourceUtils.getFile("classpath:/conf/testExcel.xlsx");
// 模板的位置,classpath这个一定要写
} catch (FileNotFoundException e) {
LOGGER.debug("===>找不到模版文件");
e.printStackTrace();
}
return vnDownload(list,file,path);
}
public ResBody vnDownload(List<Map<String,Object>> list,File file,String path) {
Map<String,Object> beans = new HashMap<String,Object>();
beans.put("list",list);
XLSTransformer transformer = new XLSTransformer();
InputStream in=null;
OutputStream out=null;
String name ="testExcel" // 文件名自己根据需要设定
try {
in=new BufferedInputStream(new FileInputStream(file));
out = new FileOutputStream(path+ name);
Workbook workbook=transformer.transformXLS(in, beans);
workbook.write(out);
out.flush();
return new ResBody(RespCode.CODE_0.getCode(),path+name);
// 把下载地址返回给前端
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in!=null){try {in.close();} catch (IOException e) {}}
if (out!=null){try {out.close();} catch (IOException e) {}}
}
return new ResBody();
}
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBHL0FWby9mZvwVZnFWbp1zczV2YvJHctM3cv1Ce-UTSU9UMVpnT5FkaNRTQU10dnRVT3lkeMBjVtJWd0ckW65UbM5WOHJWa1knW0xmMMZ3bENGMShUYvwlbj5yZtlmbkN3YuQnclZnbvN2Ztl2Lc9CX6MHc0RHaiojIsJye.jpg)
excel 模板放在这个文件夹下面,模板样子如下
把对应单元格的表头写好