SpringBoot下載Excel檔案無法開啟
阿新 • • 發佈:2022-01-03
在專案中通常會用到excel模板下載,但是在下載後卻無法開啟,下載程式碼如下:
@GetMapping("/test") public void test(HttpServletResponse response) throws IOException { String fileName = "學生資訊匯入模板.xlsx"; InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/" + fileName); response.setHeader("Access-Control-Expose-Headers", "content-disposition"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/octet-stream"); response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); int len = 0;byte bytes[] = new byte[1024]; OutputStream out = response.getOutputStream(); while ((len = in.read(bytes)) > 0) { out.write(bytes, 0, len); } in.close(); out.close(); }
檔案存放位置:
下載後開啟,顯示錯誤
在pom中新增以下程式碼即可解決。
<plugin> <groupId>org.apache.maven.plugins</groupId> <version>2.6</version> <artifactId>maven-resources-plugin</artifactId> <configuration> <encoding>UTF-8</encoding> <nonFilteredFileExtensions> <nonFilteredFileExtension>xlsx</nonFilteredFileExtension> </nonFilteredFileExtensions> </configuration> </plugin>
主要原因是maven在打包專案的時候pom.xml配置檔案裡可以配置對專案進行統一編碼,但是部分檔案可能不需要進行重新編碼,只需過濾掉不需要編碼的檔案型別即可。
就是這麼簡單,你學廢了嗎?感覺有用的話,給筆者點個贊吧 !