使用java在浏览器中下载Excel文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50566382/
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-08-10 23:41:21  来源:igfitidea点击:

Download Excel file in browser using java

javaexcelapache-poioracle-adf

提问by YLG

I have seen this question so many places, But still not able to solve my requirement.

我在很多地方都看到了这个问题,但仍然无法解决我的要求。

I have written code to generate excelsheet in Apache POI in ADF using Java and need to download it in browser as application will be in server side not always in my local machine.

我已经编写了使用 Java 在 ADF 中的 Apache POI 中生成 excelsheet 的代码,并且需要在浏览器中下载它,因为应用程序将在服务器端而不总是在我的本地机器上。

Initially I tried code:

最初我尝试了代码:

Desktop.getDesktop().open(new File(home + "/Downloads/" + "excel1" + filename + ".xls"));

It was downloading. But it is downloading only on my machine. It's not downloading on other machine.

它正在下载。但它仅在我的机器上下载。它不是在其他机器上下载。

Another solution:

另一种解决方案:

file = new File(home + "/Downloads/" + "excel" + filename + ".xls");
Runtime.getRuntime().exec("cmd.exe /C start " + file);

But it is not working..

但它不起作用..

Another solution:

另一种解决方案:

FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset();
response.setContentType(“application/vnd.ms-excel”);
response.setHeader(“Content-Disposition”, “attachment; filename=\"excel.xlsx");
workbook.write(response.getOutputStream());
fc.responseComplete();

But this solution also does not work.

但是这个解决方案也不起作用。

采纳答案by Denis Jr

I have a suggestion to try to solve your problem.

我有一个建议可以尝试解决您的问题。

I usually create a servlet that has the responsibility of downloading files in various formats: xls, pdf...

我通常会创建一个 servlet,它负责下载各种格式的文件:xls、pdf ...

Here is an example of how this can be done:

以下是如何做到这一点的示例:

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String fileName = request.getParameter("fileName");
        String contentType = null;

        if (fileName.endsWith("xls")) {
            contentType = "application/octet-stream";
        } else if (fileName.endsWith("pdf")) {
            contentType = "application/pdf";
        } else {
            throw new RuntimeException("File type not found");
        }

        byte[] file = getFileOnServer(fileName);

        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.setHeader("charset", "iso-8859-1");
        response.setContentType(contentType);
        response.setContentLength(file.length);
        response.setStatus(HttpServletResponse.SC_OK);

        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(file, 0, file.length);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    private byte[] getFileOnServer(String fileName) {
        //implement your method to get the file in byte[]
        return null;
    }

}

So, you can call your servlet by URL:

因此,您可以通过 URL 调用您的 servlet:

http://localhost:8080/downloadServlet?fileName=myExcel.xls

or Form:

或表格:

<form id="myDownloadServlet" action="downloadServlet" method="post">
    <input type="text" id="fileName" name="fileName" />
    <input type="submit" id="btnDownload" name="btnDownload" value="Download File" />
</form>

Don't forget to configure your web.xml or use the annotation @WebServlet.

不要忘记配置您的 web.xml 或使用注解@WebServlet。

I hope I've helped.

我希望我有所帮助。

回答by Arsensys

A more "professional" solution is to use Excel Api's for java, as Apache POI or JXL.

一个更“专业”的解决方案是使用 Excel Api's for java,如 Apache POI 或 JXL。

Here an example using JXL:

这是一个使用 JXL 的示例:

https://www.java-tips.org/other-api-tips-100035/93-jexcel/418-how-do-i-output-an-excel-file-from-a-servlet.html

https://www.java-tips.org/other-api-tips-100035/93-jexcel/418-how-do-i-output-an-excel-file-from-a-servlet.html

And here one more using Apache POI:

这里还有一个使用 Apache POI:

https://programtalk.com/java/download-excel-using-servlet/

https://programtalk.com/java/download-excel-using-servlet/

I hope this can helps you. Best wishes!

我希望这可以帮助你。最好的祝愿!