springboot項目實現excel靜態模板下載


excel靜態模板下載,有兩種方式:第一種,在http頭中指定輸出文件流的類型為"application/vnd.ms-excel"類型時,輸出流時就不需要添加輸出文件的后綴名;第二種,指定文件流的類型為"multipart/form-data"時,輸出流時需要判斷文件是.xls/.xlsx,並且加上后綴名。

1、方式一:(有些許問題需要改進)

controller層代碼:

 @GetMapping("/download")   //此處盡量get請求,post不知為何有問題
    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()); } } }

2、方式二:工具類可以提取整合

  @GetMapping("/download")   //此處盡量get請求,post不知為何有問題 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());
  }

注意:無論是方式一還是方式二,都是靜態模板導出,都需要將模板放在模板資源文件夾下,如下圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM