如何删除,不清空表中的行? [英] How to delete, not clear row in Sheet?

查看:0
本文介绍了如何删除,不清空表中的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何在不保留空行的情况下删除行。

我使用的是ApachePOI 3.9,使用以下代码时出现错误:

public List<MeterInfo> addToList(String patternt) throws ParseException, IOException {
    List<Object> data = new ArrayList<Object>();
    int lastRowNum = sheet.getLastRowNum();
    Row row;
    for(int i = 0; i < lastRowNum; i++){
        row = sheet.getRow(i);
        if(patternt.equals(getCurrentString(row))){
            data.add(getDataFromRow(row));
            sheet.removeRow(row);
            sheet.shiftRows(row.getRowNum() + 1, row.getRowNum() + 1, -1);
        }
    }
    saveWorkbook(new File("blabla.xlsx"));
    return data;
}

我在https://stackoverflow.com/a/3554129/6812826中找到了解决方案,但我得到了NullPointerException,因为我按每个删除的行递减lastRowNum。

新版本如下:

public List<Object> addToList(String pattern) throws ParseException, IOException {
    List<Object> data= new ArrayList<Object>();
    for (int i = 0; i <= sheet.getLastRowNum(); i++) {
        Row row = sheet.getRow(i);
        if (pattern.equals(getCurrentString(row))) {
            data.add(getMeterInfo(row));
            deleteRow(row);
        }
    }
    saveWorkbook(new File("blabla.xlsx"));
    return data;
}

private void deleteRow(Row row) {
    int lastRowNum = sheet.getLastRowNum();
    int rowIndex = row.getRowNum();
    if(rowIndex >= 0 && rowIndex < lastRowNum){
        sheet.shiftRows(rowIndex + 1, lastRowNum, -1);
    }
    if(rowIndex == lastRowNum){
        Row removingRow = sheet.getRow(rowIndex);
        if(removingRow != null){
            sheet.removeRow(removingRow);
        }
    }
}

推荐答案

尝试此代码,它应该可以工作:

for(int i = 0; i < sheet.getLastRowNum(); i++)
{
    row = sheet.getRow(i);
    if(patternt.equals(getCurrentString(row)))
    {
        data.add(getDataFromRow(row));
        // sheet.removeRow(row);    NO NEED FOR THIS LINE
        sheet.shiftRows(row.getRowNum() + 1, sheet.getLastRowNum() + 1, -1);
        i--;
    }
}
您每次删除一行都需要将i减一。并使用getLastRowNum()再次获取最后一个行号。

这篇关于如何删除,不清空表中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆