Excel文件使用Java下载 - 错误:文件已损坏

发布于 2025-01-31 06:20:21 字数 1342 浏览 3 评论 0原文

我需要在我的Spring Boot项目中从SRC/Main/Resources/DAO文件夹下载.xls文件。

文件名:daotemplate.xls

我为此写了一个代码。

 @GetMapping("/downloadDOA")
    public ResponseEntity<Object>  downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException{
   
        
        String filename = "C://Users//Sai//git//r5//src//main//resources//DOA//DOAtemplate.xls";
        File file = new File(filename);
        
        InputStreamResource iresource = new InputStreamResource(new FileInputStream(file));
        
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition","attachment;filename=" +file.getName());
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/vnd.ms-excel")).body(iresource);

        return responseEntity;
        
    
        
    }

当我使用API​​时,Excel文件正在下载,但是文件中的数据已损坏。

这是损坏数据的屏幕截图。

在此处输入图像描述

任何人都可以帮助我进行什么更改?

I need to download an .xls file from src/main/resources/DAO folder in my spring boot project.

file name : DAOtemplate.xls

I wrote a code for that.

 @GetMapping("/downloadDOA")
    public ResponseEntity<Object>  downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException{
   
        
        String filename = "C://Users//Sai//git//r5//src//main//resources//DOA//DOAtemplate.xls";
        File file = new File(filename);
        
        InputStreamResource iresource = new InputStreamResource(new FileInputStream(file));
        
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition","attachment;filename=" +file.getName());
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/vnd.ms-excel")).body(iresource);

        return responseEntity;
        
    
        
    }

When I use the api the excel file is getting downloaded but the data inside the file is getting corrupted.

Here is a screenshot of the corrupted data.

enter image description here

Can anyone pls help me what changes need to be made?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文