标签:urlencode 后缀 ping etc exception form 后缀名 style 对象
excel静态模板下载,有两种方式:第一种,在http头中指定输出文件流的类型为"application/vnd.ms-excel"类型时,输出流时就不需要添加输出文件的后缀名;第二种,指定文件流的类型为"multipart/form-data"时,输出流时需要判断文件是.xls/.xlsx,并且加上后缀名。
controller层代码:
@GetMapping("/download") public Result<String> downLoadTemplate(HttpServletResponse response) { // 获取资源中的模板文件 ClassPathResource resource = new ClassPathResource("/templates/excel/涌金数据支付明细表模板.xls"); InputStream inputStream = resource.getInputStream(); // 根据excel创建对象 Workbook workbook = WorkbookFactory.create(inputStream);
String fileName = "定义文件名"; ExcelUtil.downLoadExcel(fileName, response, workbook);
}
ExcelUtil工具类代码:
public class ExcelUtil {
//模板下载工具类 private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) { try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); workbook.write(response.getOutputStream()); } catch (IOException e) { // throw new NormalException(e.getMessage()); } } }
@GetMapping("/download") public Result<String> downLoadTemplate(HttpServletResponse response) { try { // 获取资源中的模板文件 ClassPathResource resource = new ClassPathResource("/templates/excel/涌金数据支付明细表模板.xls"); InputStream inputStream = resource.getInputStream(); // 根据不同excel创建不同对象,Excel2003版本-->HSSFWorkbook,Excel2007版本-->XSSFWorkbook Workbook wb = WorkbookFactory.create(inputStream); response.reset(); response.setContentType("multipart/form-data"); // 判断excel文件类型,下载获取到的模板并重新命名 System.out.println(wb.getClass().getSimpleName()); if (wb.getClass().getSimpleName().equals("HSSFWorkbook")) { response.setHeader("Content-Disposition", "attachment; filename=" + new String("定义文件名称".getBytes("UTF-8"), "iso8859-1") + ".xls"); } else { response.setHeader("Content-Disposition", "attachment; filename=" + new String("定义文件名称".getBytes("UTF-8"), "iso8859-1") + ".xlsx"); } wb.write(response.getOutputStream());
}
注意:无论是方式一还是方式二,都是静态模板导出,都需要将模板放在模板资源文件夹下,如下图:
标签:urlencode 后缀 ping etc exception form 后缀名 style 对象
原文地址:https://www.cnblogs.com/H-Dream/p/11408368.html