如何删除,不清除工作表中的行?阿帕奇兴趣点 [英] How to delete, not clear row in Sheet ? Apache POI

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

问题描述

我遇到了一个问题.我不知道如何删除行而不留下后记空行.

I've faced with a problem. I don't know how to delete row without leaving afterwords empty row.

我正在使用 Apache-POI 3.9,但使用下一个代码时出现错误:

I am using Apache-POI 3.9 and I am getting error using next code :

 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,但我正在获取空指针,因为我通过每个删除行减少 lastRowNum.

I've found the solution: https://stackoverflow.com/a/3554129/6812826 , but I am getting null pointer because I am decrease lastRowNum by each deleting row.

这是新版本:

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

最后更新:ManishChristian 帮我解决了这个问题!

LAST UPDATE: ManishChristian helped me resolve this problem !

推荐答案

试试这个代码,应该可以:

Try this code, it should work:

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() 再次获取最后一行编号.

You need to decrease i by one every time you delete one row. And get the last row number again by using getLastRowNum().

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

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