我遇到了一个问题.
我不知道如何在不将后记留空的情况下删除行.
我正在使用Apache-POI 3.9,使用下一个代码时出现错误:
public List addToList(String patternt) throws ParseException, IOException {
List data = new ArrayList();
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,所以我得到了空指针.
这是新版本:
public List addToList(String pattern) throws ParseException, IOException {
List data= new ArrayList();
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帮助我解决了这个问题!
解决方法:
试试下面的代码,它应该可以工作:
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()再次获取最后一行.
标签:apache-poi,java,excel
来源: https://codeday.me/bug/20191026/1934116.html