Springboot 讀取 resource 目錄下的Excel文件並下載


如果 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>```


免責聲明!

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



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