Excel .xlsx file not opening after downloading the file from the server in java

给你一囗甜甜゛ 提交于 2019-12-24 02:23:44

问题


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 .


回答1:


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();



回答2:


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


来源:https://stackoverflow.com/questions/25782961/excel-xlsx-file-not-opening-after-downloading-the-file-from-the-server-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!