springboot下載resources路徑下的excel檔案
阿新 • • 發佈:2022-03-15
Excel檔案位置:
後臺Controller程式碼如下:
import org.apache.commons.io.IOUtils; import org.jeecg.common.aspect.annotation.AutoLog; import org.springframework.core.io.ResourceLoader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.InputStream; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @RestController @RequestMapping("") public class DownloadExcelTemplateController { @Resourceprivate ResourceLoader resourceLoader; /** * 下載模板 * * @param response */ @AutoLog(value = "下載匯入模板") @RequestMapping(value = "/downloadTemp") public void downloadExcel(HttpServletResponse response) { InputStream inputStream = null; ServletOutputStream servletOutputStream= null; try { String filename = "匯入模板.xls"; String path = "excel/bbb.xls"; org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:" + path); response.setContentType("application/vnd.ms-excel"); response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate"); response.addHeader("charset", "utf-8"); response.addHeader("Pragma", "no-cache"); String encodeName = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString()); response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName); inputStream = resource.getInputStream(); servletOutputStream = response.getOutputStream(); IOUtils.copy(inputStream, servletOutputStream); response.flushBuffer(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (servletOutputStream != null) { servletOutputStream.close(); } if (inputStream != null) { inputStream.close(); } // jvm的垃圾回收 System.gc(); } catch (Exception e) { e.printStackTrace(); } } } }
如果下載的excel檔案提示損壞無法開啟,在pom.xml檔案中新增避免壓縮的外掛
<build> <plugins> <!-- 避免excel檔案壓縮破壞 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>3.2.0</version> <configuration> <encoding>UTF-8</encoding> <nonFilteredFileExtensions> <nonFilteredFileExtension>xls</nonFilteredFileExtension> </nonFilteredFileExtensions> </configuration> </plugin> </plugins> </build>