前端代码如下:
<a class="btn btn-warning" onclick="exportExcel()">下载</a>
function exportExcel() {
window.location.href = prefix+ "/export";
}
模板位置如下:
后台代码如下:
/**
* 下载excel模板
*
* @return
*/
@RequestMapping("/export")
public void getApplicationTemplate(HttpServletRequest req, HttpServletResponse res) {
String fileName = "test.xlsx";
Resource resource = new ClassPathResource("modifyTemplate/".concat(fileName));
if (!resource.exists()) {
throw new RuntimeException("下载模板不存在!");
}
try {
res.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//设置响应对象
setAttachmentResponseHeader(res, fileName);
//输出指定文件
writeBytes(resource.getFile().getPath(), res.getOutputStream());
} catch (IOException e) {
throw new RuntimeException("下载文件发生不可预期的错误");
}
}
public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
String percentEncodedFileName = percentEncode(realFileName);
StringBuilder contentDispositionValue = new StringBuilder();
contentDispositionValue.append("attachment; filename=")
.append(percentEncodedFileName)
.append(";")
.append("filename*=")
.append("utf-8''")
.append(percentEncodedFileName);
response.setHeader("Content-disposition", contentDispositionValue.toString());
}
/**
* 百分号编码工具方法
*
* @param s 需要百分号编码的字符串
* @return 百分号编码后的字符串
*/
public static String percentEncode(String s) throws UnsupportedEncodingException {
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
return encode.replaceAll("\\+", "%20");
}
/**
* 输出指定文件的byte数组
*
* @param filePath 文件路径
* @param os 输出流
* @return
*/
public static void writeBytes(String filePath, OutputStream os) throws IOException {
FileInputStream fis = null;
try {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException(filePath);
}
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int length;
while ((length = fis.read(b)) > 0) {
os.write(b, 0, length);
}
} catch (IOException e) {
throw e;
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}