我正在尝试删除具有特定数据的 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;
}
}
}
}
最佳答案
不要忘记应用更改后需要保存工作簿。添加这些:
FileOutputStream out = new FileOutputStream ("file name");
book.write(out);
另请注意,如果所需行是最后一行,则应调用 sheet.removeRow(rowIndex);
而不是 shiftRows
。
另一个观察结果是,您在运行时会跳过 for
循环中的最后一行,直到 LastRowNum-1
。应该是:
for (int rowIndex = 0; rowIndex < sheet.getLastRowNum(); rowIndex++) {
}
关于java - 使用 Apache_poi 删除包含特定文本的 Excel 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24836693/