【问题标题】:Apache POI export to excel in web browserApache POI 导出到 web 浏览器中的 excel
【发布时间】:2016-09-28 06:22:00
【问题描述】:

我想在浏览器中导出 excel 文件并在浏览器下载位置下载文件(与浏览器中发生的任何下载相同)。我正在使用以下 servlet 导出文件,但它不显示下载或不下载到浏览器默认下载位置。但文件已导出到项目位置。

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    // PrintWriter out = response.getWriter();

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition",
            "attachment; filename=filename.xls");
    try {
        // ExportClass export = new ExportClass();
        // export.export();

        XSSFWorkbook workbook = new XSSFWorkbook();
        // Create a blank sheet
        XSSFSheet spreadsheet = workbook.createSheet(" Employee Info ");
        // Create row object
        XSSFRow row = spreadsheet.createRow(1);
        XSSFCell cell;
        cell = row.createCell(1);
        cell.setCellValue("AGE");
        cell = row.createCell(2);
        cell.setCellValue("ID");
        cell = row.createCell(3);
        cell.setCellValue("NAME");

        int i = 2;
        DbCon db = new DbCon();
        ArrayList<Student> students = db.getStudentList();

        for (int x = 0; x < students.size(); x++) {

            row = spreadsheet.createRow(i);
            cell = row.createCell(1);
            cell.setCellValue(students.get(x).studentAge);
            cell = row.createCell(2);
            cell.setCellValue(students.get(x).studentID);
            cell = row.createCell(3);
            cell.setCellValue(students.get(x).stuntName);
            i++;
        }

        // Write the workbook in file system

        OutputStream out = response.getOutputStream();
        System.out.println("going to export");
        workbook.write(out);
        out.close();
        System.out.println("exceldatabase.xlsx written successfully");

    }

请帮助我找出问题所在。谢谢。

【问题讨论】:

  • 代码会被调用吗?有趣的是你正在做一个 POST 来获取一个文件
  • 还有你为什么要使用 POI 来流式传输文件,只需使用普通的 FileInputStream
  • 我怀疑您需要设置内容长度。 response.setContentLength(???)。要为此获取工作簿的大小,请参阅stackoverflow.com/questions/28122474/…。但我会使用response.setContentLength 而不是response.setHeader("Content-Length", ...)

标签: java excel apache-poi


【解决方案1】:

您可以使用 ByteArrayOutputStream 导出您的 excel 文件

  // Write the workbook in file system

    response.setContentType("application/octet-stream");

    response.setHeader("Content-Disposition", "attachment; filename=exceldatabase.xlsx");



    ByteArrayOutputStream out = new ByteArrayOutputStream();
    workbook.write(out);
    ByteArrayInputStream stream = new 
    ByteArrayInputStream(out.toByteArray());
    IOUtils.copy(stream, response.getOutputStream());

【讨论】:

    猜你喜欢
    • 2014-12-07
    • 2015-04-22
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多