java 如何使excel文件可下载

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

How to make excel file to be downloadable

javabrowserdownload

提问by n92

I have generated excel report and i want the file to be downloaded by the user ,so how to set the response properties (content type) .

我已经生成了 excel 报告,我希望用户下载文件,那么如何设置响应属性(内容类型)。

回答by Nicolas Modrzyk

You need to set the headers and content type like this:

您需要像这样设置标题和内容类型:

    response.setHeader "Content-disposition", "attachment;filename=myExcel.xls"
    response.contentType = "application/vnd.ms-excel"

Then stream the content in the response.

然后在响应中流式传输内容。

Edit: If you need to set the content length:

编辑:如果您需要设置内容长度:

    response.contentLength = 100

Content length documented in the javadoc

javadoc 中记录的内容长度

回答by Basanth Roy

response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "Attachment;Filename=\"MyFile.xls\"");

回答by Bhola

You have To Add jxl jar

你必须添加jxl jar

and

Try this code :

试试这个代码:

@WebServlet("/Reportexel")
public class Reportexel extends HttpServlet
{
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        try
        {
            response.setHeader("Content-disposition", "attachment; filename=kbdemo.xls");
            response.setContentType("application/vnd.ms-excel");
            WritableWorkbook workbook = Workbook.createWorkbook(response.getOutputStream());    
            WritableSheet worksheet = workbook.createSheet("Sheet 1",0);

            Label lbl = new Label(1,1,"Hello");
            Label lbl1 = new Label(1,2,"Hi...");

            worksheet.addCell(lbl);
            worksheet.addCell(lbl1);

            workbook.write();
            workbook.close();
        }
        catch(Exception e)
        {
            System.err.println("Main Error : "+e);
        }
    }
}