无法使用POI在Excel中写入多行

时间:2011-02-11 10:30:01

标签: java apache-poi

我有一种情况,我将阅读多行,并在一些逻辑后,我需要在Excel工作表中写行。我正在使用Apache POI来实现此目的。但是,我面临的问题是,只有最后一行(来自循环)被写入Excel

有人可以帮我解决这个问题或提供一些代码片段吗?

由于

1 个答案:

答案 0 :(得分:15)

    Workbook wb = new XSSFWorkbook();   //or new HSSFWorkbook();
    Sheet sheet = wb.createSheet();

    Row row = sheet.createRow(2);
    Cell cell = row.createCell(2);
    cell.setCellValue("Use \n with word wrap on to create a new line");

    //to enable newlines you need set a cell styles with wrap=true
    CellStyle cs = wb.createCellStyle();
    cs.setWrapText(true);
    cell.setCellStyle(cs);

    //increase row height to accomodate two lines of text
    row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));

    //adjust column width to fit the content
    sheet.autoSizeColumn((short)2);

    FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
    wb.write(fileOut);
    fileOut.close();