在項(xiàng)目中經(jīng)常會(huì)用到文件下載的功能,比如下載excel模板,這里簡單記錄一下實(shí)現(xiàn)過程
1、將模板文件放到項(xiàng)目資源文件目錄中,也可以自定義其他位置,只要通過路徑能找到該文件就行:
?2、controller層寫下載的接口文章來源:http://www.zghlxwxcb.cn/news/detail-514236.html
/**
* 下載導(dǎo)入模板
*/
@GetMapping("downloadExcel")
public void downloadExcel(HttpServletResponse httpServletResponse) {
InputStream inputStream = null;
try (ServletOutputStream outputStream = httpServletResponse.getOutputStream()) {
//設(shè)置響應(yīng)頭信息,包括下載后的文件名和編碼等
httpServletResponse.addHeader("content-disposition", String.format("attachment;filename= %s", URLEncoder.encode("導(dǎo)入模板.xlsx", "utf-8")));
httpServletResponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
httpServletResponse.setCharacterEncoding("UTF-8");
//在文件夾里獲取到文件并轉(zhuǎn)為流
inputStream = new ClassPathResource("/senseXlsx.xlsx").getInputStream();
byte[] b = streamToByteArray(inputStream);
httpServletResponse.getOutputStream().write(b);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3、前端直接調(diào)用這個(gè)接口就可以實(shí)現(xiàn)下載啦文章來源地址http://www.zghlxwxcb.cn/news/detail-514236.html
到了這里,關(guān)于Java下載Excel模板文件的實(shí)現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!