在java中从服务器下载文件后,Excel .xlsx文件不会打开 [英] Excel .xlsx file not opening after downloading the file from the server in java

查看:2572
本文介绍了在java中从服务器下载文件后,Excel .xlsx文件不会打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

    }

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

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 .

推荐答案

我强烈建议您使用 HSSFWorkbook 类来创建你的excel文件。创建之后(创建过程请参阅:此示例)您可以将其内容写入回复:

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

这篇关于在java中从服务器下载文件后,Excel .xlsx文件不会打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆