简体   繁体   English

使用Apache POI将列添加到Excel

[英]Adding column to Excel using Apache POI

I was wondering about adding new column in a .xlsx file using apache poi. 我想知道使用apache poi在.xlsx文件中添加新列。 But I could not found anything. 但我找不到任何东西。 Is there any way to do this? 有没有办法做到这一点? Or is there exists any other library to solve this? 或者是否存在任何其他库来解决这个问题? Thanks in advance. 提前致谢。

There is no explicit way of doing this using apache POI. 使用apache POI没有明确的方法。 If you know the number of rows and the number of columns that you need, you can first create the required number of rows and then create the corresponding cells in the rows. 如果您知道所需的行数和列数,则可以先创建所需的行数,然后在行中创建相应的单元格。 You can refer to the code below if needed. 如果需要,您可以参考下面的代码。

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

If you have excel file with existing rows, well defined, the fastest way to add column is to iterate once over the rows and in each iterations add a column at end as beflow code 如果你有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");
    }

Hope it helps, I assume your first row is header, the rest will be empty for future modifications 希望它有所帮助,我假设你的第一行是标题,其余的将是空的,以便将来修改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM