使用Apache POI向Excel添加列

7

我想知道如何使用Apache POI在.xlsx文件中添加新列。但是我没有找到相关资料。有没有办法解决这个问题?或者是否有其他库可以解决这个问题?提前感谢。


通常情况下,您需要创建行,然后添加“列作为单元格”。请参见http://stackoverflow.com/questions/18213657/java-poi-excel-creating-new-column-and-new-rows。 - Jayan
2个回答

4
如果您有一个已定义好的包含现有行的Excel文件,添加列的最快方法是在每次迭代中将一列添加到末尾,如下所示的代码。
    FileInputStream excelFile = new FileInputStream(new File(fileDirectory+file));
    Workbook workbook = new XSSFWorkbook(excelFile);
    Sheet datatypeSheet = workbook.getSheetAt(0);
    Iterator<Row> iterator = datatypeSheet.iterator();

    // Add additional column for results
    while (iterator.hasNext()) {
        Row currentRow = iterator.next();
        Cell cell = currentRow.createCell(currentRow.getLastCellNum(), CellType.STRING);
        if(currentRow.getRowNum() == 0)
            cell.setCellValue("NEW-COLUMN");
    }

希望这能有所帮助,我假设你的第一行是标题行,其余部分将为空以便进行未来修改。

1

使用apache POI没有明确的方法来实现这一点。如果您知道所需的行数和列数,可以先创建所需数量的行,然后在行中创建相应的单元格。如有需要,可以参考以下代码。

for(row=0;row<maxRowLimit;row++){
    myRow = sheet.getRow(row);
          if (myRow == null) {
            myRow = sheet.createRow(row);
            myCell=myRow.getCell(columnNumber);
            if (myCell == null)
              myRow.createCell(columnNumber); 
          }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接