简体   繁体   English

使用Apache_poi删除包含特定文本的Excel行

[英]delete Excel row containing specific text using Apache_poi

I am trying to remove an Excel row which has specific data.Ex:delete a row where student roll number is 1.Below is what i have done so far but it won't work. 我正在尝试删除包含特定数据的Excel行。例如:删除学生卷数为1的行。以下是我到目前为止所做的操作,但将不起作用。

   String personal=personal1.getSelectedItem().toString();
   String roll=classper.getText();
   String ps="personal";
   InputStream myxls = new FileInputStream("D:\\" + personal + ps + ".xls");
   Workbook book = new HSSFWorkbook(myxls);
   Sheet sheet = book.getSheetAt(0);
   Row Row = null;
   Cell Cell = null;
   int LastRowNum = sheet.getLastRowNum();
   for(int RowNum= 0;RowNum<LastRowNum-1;RowNum++){
        Row=sheet.getRow(RowNum);
        for(int CellNum = 0; CellNum<Row.getLastCellNum();CellNum++){
           Cell = Row.getCell(CellNum);
           String TextInCell=Cell.toString();
           if(TextInCell.contains(roll)){
              sheet.shiftRows(RowNum+1, LastRowNum, -1);
              LastRowNum--;
              RowNum--;
              break;
           }
        }
    }
   }

Don't forget that you need to save the workbook after you apply changes. 不要忘记应用更改后需要保存工作簿。 Add these: 添加以下内容:

FileOutputStream out = new FileOutputStream ("file name");
book.write(out);

Also note that if the desired row is the last one, you should call sheet.removeRow(rowIndex); 还要注意,如果所需的行是最后一行,则应调用sheet.removeRow(rowIndex); instead of shiftRows . 而不是shiftRows

Another observation, you are skipping the last row in the for loop as you are running until LastRowNum-1 . 另一观察,您正在运行时跳过for循环的最后一行,直到LastRowNum-1为止。 It should be: 它应该是:

for (int rowIndex = 0; rowIndex < sheet.getLastRowNum(); rowIndex++) {
}

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

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