Excel .xlsx file not opening after downloading the

2019-07-25 08:19发布

Here is my sample code. I am using eclipse , tomcat server .Browser as 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();

    }

I am getting the List of Student. But when i am opening the downloaded file file getting error saying that file format or extention is not valid. My downloaded file is .xlsx .

2条回答
太酷不给撩
2楼-- · 2019-07-25 08:25

It is not so much an .xlsx file, more a CSV or tab separated value text file. It fakes to be an Excel file; and yes, then Excel opens it correctly,

Try to read it with NotePad. You also can make a .xlsx file with NotePad to check whether the trick works.

The following tries:

  • .xls
  • A Windows \r\n (CR+LF) line ending. Maybe the server is Linux and delivers \n (LF).
  • A defined encoding.

Then

    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();
查看更多
Anthone
3楼-- · 2019-07-25 08:33

I strongly recommend you to use HSSFWorkbook class to create your excel file. After its created (for creation process see: this example) you can write its contents to response like this:

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);
查看更多
登录 后发表回答