从java中的服务器下载文件后,Excel .xlsx文件无法打开

问题描述 投票:1回答:2

这是我的示例代码。我使用eclipse,tomcat服务器.Browser作为IE9。

protected void service(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");


        ServletContext context = request.getServletContext();
        @SuppressWarnings("unchecked")
        List<Student> students = (List<Student>) context.getAttribute("students");
        PrintWriter out = response.getWriter();
        for(Student student:students){
            out.println(student.getId()+"\t"+student.getName());
        }
        out.close();

    }

我正在获得学生名单。但是当我打开下载的文件文件时收到错误,说文件格式或扩展名无效。我下载的文件是.xlsx。

java excel java-ee servlets
2个回答
0
投票

它不是一个.xlsx文件,更多是CSV或制表符分隔值文本文件。它假装成一个Excel文件;是的,然后Excel正确打开它,

尝试用NotePad阅读它。您还可以使用NotePad创建.xlsx文件,以检查该技巧是否有效。

以下尝试:

  • 的.xls
  • Windows \r\n(CR + LF)行结束。也许服务器是Linux并提供\n(LF)。
  • 定义的编码。

然后

    response.setEncoding("UTF-8");
    response.setContentType("application/vnd.ms-excel");

    ServletContext context = request.getServletContext();
    @SuppressWarnings("unchecked")
    List<Student> students = (List<Student>) context.getAttribute("students");
    PrintWriter out = response.getWriter();
    out.print("\uFEFF"); // UTF-8 BOM, redundant and ugly
    for(Student student:students){
        out.printf("%s\t%s\r\n", student.getId(), student.getName());
    }
    //out.close();

0
投票

我强烈建议您使用HSSFWorkbook类来创建您的Excel文件。在创建之后(对于创建过程请参阅:this example),您可以将其内容写入响应,如下所示:

Workbook workbook = new XSSFWorkbook();

// Add sheet(s), colums, cells and its contents to your workbook here ...

// First set response headers
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=YourFilename.xlsx");

// Get response outputStream
ServletOutputStream outputStream = response.getOutputStream();

// Write workbook data to outputstream
workbook.write(outputStream);
© www.soinside.com 2019 - 2024. All rights reserved.