Apache POI - 删除并向上移动Cell

时间:2017-09-12 21:07:07

标签: java excel apache apache-poi delete-row

我正在使用Apache POi HSSF库导入Excel表并将其导出到我的应用程序(tableview)。我想在Excel中使用特定ID从Excel中删除一行。有用。我的问题是,在我删除一行后,有一个空行,它删除的行多于所选行。大家可以帮忙吗?

FileInputStream inp = new FileInputStream(
            "...............";

    HSSFWorkbook wb = (HSSFWorkbook) WorkbookFactory.create(inp);
    HSSFSheet sheet = wb.getSheetAt(0);

    String selectedid = auftragTabelle.getSelectionModel().getSelectedItem().getId();

    int rowIndex = 0;
    int lastRowNum = sheet.getLastRowNum();

    for (Row row : sheet) {
        for (Cell cell : row) {
            if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                if (cell.getRichStringCellValue().getString().trim().equals(selectedid)) {
                    rowIndex = cell.getRowIndex();
                }
            }
        }
    }

    if (rowIndex >= 0 && rowIndex < lastRowNum) {
        sheet.shiftRows(rowIndex, lastRowNum, -1);
    }

    if (rowIndex <= lastRowNum) {
        HSSFRow removingRow = sheet.getRow(rowIndex);

        if (removingRow != null) {
            sheet.removeRow(removingRow);
        }
    }

    OutputStream out = new FileOutputStream(
            "............";

    wb.write(out);
    out.close();

}

1 个答案:

答案 0 :(得分:0)

以下是我将如何做的一个例子:

public static void main(String[] args) throws InvalidFormatException, IOException {
    FileInputStream inp = new FileInputStream(FILENAME);

    HSSFWorkbook wb = (HSSFWorkbook) WorkbookFactory.create(inp);
    HSSFSheet sheet = wb.getSheetAt(0);

    String selectedid = "3";

    int rowIndex = getRowIndexOfId(sheet, selectedid);

    removeRow(sheet, rowIndex);

    OutputStream out = new FileOutputStream(FILENAME);

    wb.write(out);
    out.close();
}
private static int getRowIndexOfId(HSSFSheet sheet, String selectedid) {
    DataFormatter formatter = new DataFormatter();
    for (Row row : sheet) {
        for (Cell cell : row) {
            if (formatter.formatCellValue(cell).trim().equals(selectedid)) {
                return row.getRowNum();
            }
        }
    }
    return -1;
}
private static void removeRow(HSSFSheet sheet, int rowIndex) {
    if (rowIndex >= 0) {
        sheet.removeRow(sheet.getRow(rowIndex));
        if(rowIndex < sheet.getLastRowNum()) {
            sheet.shiftRows(rowIndex + 1, sheet.getLastRowNum(), -1);
        }
    }
}

一些评论:

  1. 您可以使用DataFormatter类格式化单元格值(以便比较任何单元格值)

  2. 我 - 像你一样 - 比较细胞中的任何细胞;对我来说,典型的用例是搜索每行的第一个col来查找id。如果您愿意,请相应地调整代码。

  3. 我最后做了换档行,这应该会更好。