如何使excel文件可下载

时间:2011-08-03 05:12:21

标签: java browser download

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

3 个答案:

答案 0 :(得分:9)

您需要设置标题和内容类型,如下所示:

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

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

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

    response.contentLength = 100

javadoc

中记录的内容长度

答案 1 :(得分:2)

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

答案 2 :(得分:0)

您必须添加jxl jar

试试这段代码:

@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);
        }
    }
}