赞
踩
例如下载/resources/excel/template.xlsx
@GetMapping("/download")
public void downloadFile(HttpServletRequest request,
HttpServletResponse response) {
String fullFileName = "excel/template.xlsx";
ExcelUtils.exportLocalExcel(request, response, fullFileName);
}
ExcelUtils.java
public class ExcelUtils { /** * 导出本地Excel * * @param httpRequest 请求信息 * @param httpResponse 响应信息 * @param pathFileName 带路径的文件名字 */ public static void exportLocalExcel(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String pathFileName) throws Exception { String[] split = pathFileName.split("/"); ClassPathResource classPathResource = new ClassPathResource(pathFileName); InputStream fis = classPathResource.getInputStream(); httpResponse.setContentType("application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); String rawFileName = split[split.length - 1]; String fileName = FileNameUtil.getPrefix(rawFileName); String suffix = FileNameUtil.getSuffix(rawFileName); httpResponse.setHeader("Content-Disposition", "attachment;filename=" + getFileName(fileName, httpRequest) + "." + suffix); ServletOutputStream outputStream = httpResponse.getOutputStream(); if (fis.available() != 0) { httpResponse.setStatus(200); } IOUtils.copy(fis, outputStream); fis.close(); outputStream.flush(); outputStream.close(); } /** * 处理文件名字编码 * * @param fileName 文件名字 * @param request 请求信息 * @return 编码后文件名 * @throws Exception 异常信息 */ private static String getFileName(String fileName, HttpServletRequest request) throws Exception { String ua = request.getHeader("User-Agent").toLowerCase(); if (ua.contains("macintosh") && !ua.contains("chrome")) { //浏览器: safari return new String(fileName.getBytes(), "ISO8859-1"); } //默认utf-8 return URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。