Java HttpServlet 如何下载excel文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26611424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:14:16  来源:igfitidea点击:

Java HttpServlet how to download excel file

javaexcelhttpservletsdownload

提问by MeesterPatat

I am trying to add a function to my web app which lets the users download an excel file.

我正在尝试向我的 Web 应用程序添加一个功能,该功能允许用户下载 Excel 文件。

I'm trying to achieve this with the following code:

我正在尝试使用以下代码实现这一目标:

@Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        File file = new File("d:/test/test.xls");
        response.setContentType("application/xls");
        response.addHeader("Content-Disposition", "attachment; filename=test.xls");
        response.setContentLength((int) file.length());

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            OutputStream responseOutputStream = response.getOutputStream();
            int bytes;
            while ((bytes = fileInputStream.read()) != -1) {
                responseOutputStream.write(bytes);
            }
            fileInputStream.close();
            responseOutputStream.close();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

I'm able to download the excel file with the above code, however the file is corrupted. If I open it with microsoft excel, I get a popup with the message:

我可以使用上述代码下载excel文件,但是文件已损坏。如果我用 microsoft excel 打开它,我会收到一个带有消息的弹出窗口:

"the file format and extension of don't match. the file could be corrupted or unsafe".

“文件格式和扩展名不匹配。文件可能已损坏或不安全”。

And the excel file is empty.

并且excel文件是空的。

After running the code, the original file(d:/test/test.xls) gets also corrupted.

运行代码后,原始文件(d:/test/test.xls)也被损坏。

What am I doing wrong?

我究竟做错了什么?

回答by Buhake Sindi

The official MIME type for Excel file .xlsis application/vnd.ms-exceland for .xlsxis application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.

官方的MIME类型的Excel文件.xlsapplication/vnd.ms-excel.xlsxIS application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Also, I would suggest doing response.reset()prior to writing to the output stream and responseOutputStream.flush()(important) prior to closing the response.

另外,我建议response.reset()在写入输出流responseOutputStream.flush()之前和(重要)在关闭response.

回答by K M PATEL

Try below code :

试试下面的代码:

    File file = null;
    InputStream in = null;
    OutputStream outstream = null;
    try {
      response.reset();
      in = new FileInputStream(file);
      response.setContentType("application/vnd.ms-excel");
      response.addHeader("content-disposition", "attachment; filename=data.xls");
      outstream = response.getOutputStream();
      IOUtils.copyLarge(in, outstream);
     }
    catch (Exception e) {
        out.write("Unable to download file");
    }finally {
        IOUtils.closeQuietly(outstream);
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        if (file != null)
            file.delete();
    }

dont forgot to add apache commons-io-2.4 in your dependency

不要忘记在您的依赖项中添加 apache commons-io-2.4