Springboot 讀取 resource 目錄下的Excel檔案並下載
阿新 • • 發佈:2022-03-10
如果 inputStream 為null ,或者提示 檔案路徑不存在,執行 mvn clean 並 重啟專案,檢視target 目錄下是否存在該檔案
@GetMapping("/download") public void download(HttpServletResponse response) { try { String filename = "測試.xls"; OutputStream outputStream = response.getOutputStream(); // 獲取springboot resource 路徑下的檔案 InputStream inputStream = this.getClass().getResourceAsStream("/excel/text.xls"); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;fileName=" + new String(filename.getBytes("utf-8"), "iso-8859-1")); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.flush(); } catch (Exception e) { throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.toString()); } }
pom 新增如下,否則 excel檔案中文亂碼,以及各種莫名其妙的問題
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> <configuration> <encoding>UTF-8</encoding> <nonFilteredFileExtensions> <nonFilteredFileExtension>xls</nonFilteredFileExtension> <nonFilteredFileExtension>xlsx</nonFilteredFileExtension> <nonFilteredFileExtension>dat</nonFilteredFileExtension> </nonFilteredFileExtensions> </configuration> </plugin>```