无法使用POI下载xlsx文件

时间:2016-12-06 10:38:05

标签: spring-mvc servlets apache-poi

enter image description here您正在使用poi poc在webapplication中生成xlsx文件我能够独立地渲染excel但是当我在我的项目中集成codebase时,我得到了以下错误。error

下面是在webapplication中下载xlsx文件的代码库

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet spreadsheet = workbook.createSheet("Sheet1");
    XSSFRow row = spreadsheet.createRow(0);
    XSSFCell cell;


    while (response.nextResultSet()) {
        resultSet = response.getResultSet();
        Object[] columnMetaData = resultSet.getColumnNames();
        int columnCount = columnMetaData.length;
          //Columns Loop 
        ArrayList<String> columns = new ArrayList<String>();
        for (int i = 1; i < columnCount; i++) {
            String columnName = (String) columnMetaData[i];
            columns.add(columnName);
            cell = row.createCell(i-1);
            cell.setCellValue(columnName);
         } 

        int i=1;
          while (resultSet.nextRow()) {
             row = spreadsheet.createRow(i);
             i++; // counter for each row of data
            for (int j = 0; j < columnMetaData.length; j++)
            {
                String keyVal = String.valueOf(columnMetaData[j]);
                String value = (String)resultSet.getValue(keyVal);
                cell = row.createCell(j);
                cell.setCellValue(value);


            }
        }

      log.info("value if i--->" + i);     

      for (int k = 1; k < columnCount; k++) {
            spreadsheet.autoSizeColumn(k-1);
        }
    }   

    ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
    workbook.write(outByteStream);

    context.getResponse().setHeader("content-disposition", "inline;filename=" + calendar.getTimeInMillis() + ".xlsx");
        context.getResponse().setContentType("application/Excel");
        context.getRequest().setAttribute("called_from", "excel");
        //context.getResponse().setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //context.getResponse().setHeader("Content-Disposition", "attachment; filename=testxls.xlsx");
    }

       OutputStream os = null;


        os = context.getResponse().getOutputStream();
        byte [] outArray = is.toByteArray();
        context.getResponse().setContentLength(outArray.length);
        os.write(outArray);
        log.info(os.toString());
        os.flush();

0 个答案:

没有答案