赞
踩
controller层代码
@ApiOperation(value="导出模板")
@RequestMapping(value="/getTemplate" , method= RequestMethod.GET)
@ResponseBody
public void getTemplate(HttpServletRequest req,HttpServletResponse res) throws IOException {
standingBookService.getTemplate(req, res);
}
serviceImpl代码
public void getTemplate(HttpServletRequest req, HttpServletResponse res) throws IOException {
String templateName = "standingBookTemplate";
String exportName = "template";
ExcelUtil.downloadExcelTemplate(req, res, templateName, exportName);
}
导出模板路径
工具箱代码
/**
* 下载批量导入模板
* @param HttpServletRequest
* @param HttpServletResponse
* @param templateName execl模板名称
* @param exportName 导出表单名称
* @throws IOException
*/
public static void downloadExcelTemplate(HttpServletRequest req,HttpServletResponse res,String templateName,
String exportName) throws IOException{
String fullFileName = req.getServletContext().getRealPath("/doc/import/excelTemplate");
fullFileName += (File.separator + templateName + ".xls");
String export = "";
if(DataValidUtil.isEmpty(exportName)){
export = templateName;
}else{
export = exportName;
}
String userAgent = req.getHeader("USER-AGENT");
//文件下载乱码问题
if (StringUtils.contains(userAgent.toUpperCase(),"MSIE")||StringUtils.contains(userAgent,"Trident")) {
export = URLEncoder.encode(export, "UTF-8");
} else {
export = new String(export.getBytes("UTF-8"), "ISO8859-1");
}
//设置Content-Disposition
res.setHeader("Content-disposition","attachment; filename="+export+".xls");
//设置文件MIME类型
//res.setContentType("application/vnd.ms-excel");
//前端框架自定义类型
res.setContentType("application/export.file");
OutputStream out = res.getOutputStream();
FileInputStream in = new FileInputStream(fullFileName);
res.setCharacterEncoding("UTF-8");
byte[] b = new byte[1024];
int n = -1;
while((n=in.read(b))!=-1){
out.write(b, 0, n);
}
in.close();
out.close();
}
vue前端写法
//模板下载 getTemplate(){ const that = this; window.location='/test/test/getTemplate';//正确写法,直接访问你的请求路径 //这种写法会导致后台不报错,但是前端无导出效果 /*window.axios.get('/test/test/getTemplate',{responseType: 'arraybuffer'}).then((res) => { }).catch((err) => { });*/ },
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。