问题
I want to delete blank row from Excel sheet using POI.
We have method like shiftRow()
or removeRow()
but its not for use
in this case. Please help me to get it done.
回答1:
Please try following piece of code. It works for me as well when more than one consecutive blank rows existing.
for(int i = 0; i < sheet.getLastRowNum(); i++){
if(sheet.getRow(i)==null){
isRowEmpty=true;
sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
i--;
continue;
}
for(int j =0; j<sheet.getRow(i).getLastCellNum();j++){
if(sheet.getRow(i).getCell(j).toString().trim().equals("")){
isRowEmpty=true;
}else {
isRowEmpty=false;
break;
}
}
if(isRowEmpty==true){
sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
i--;
}
}
回答2:
Although not tested, try this:
HSSFSheet sheet = workBook.getSheetAt(0);
HSSFRow row = sheet.getRow(0);
sheet.removeRow(row);
回答3:
Changes to @Sankumarsingh code to make it work
@Sankumarsingh code did not work for me as it was not removing empty first row. Fix for this issue is:
private void removeEmptyRows(XSSFSheet sheet) {
Boolean isRowEmpty = Boolean.FALSE;
for(int i = 0; i <= sheet.getLastRowNum(); i++){
if(sheet.getRow(i)==null){
isRowEmpty=true;
sheet.shiftRows(i + 1, sheet.getLastRowNum()+1, -1);
i--;
continue;
}
for(int j =0; j<sheet.getRow(i).getLastCellNum();j++){
if(sheet.getRow(i).getCell(j) == null ||
sheet.getRow(i).getCell(j).toString().trim().equals("")){
isRowEmpty=true;
}else {
isRowEmpty=false;
break;
}
}
if(isRowEmpty==true){
sheet.shiftRows(i + 1, sheet.getLastRowNum()+1, -1);
i--;
}
}
}
回答4:
This is a way to break the reading of cells when they have deleted rows taken as non-blank rows
while(cellsIterator.hasNext()) {
Cell currentCell = cellsIterator.next();
if(currentCell.getCellType() == Cell.CELL_TYPE_BLANK) {
this.currentArraySheet.put("Headers",this.currentArraySheetHeaders);
this.currentArraySheet.put("Rows",this.currentArraySheetRows);
return;
}
if (currentCell.getCellTypeEnum() == CellType.STRING) {
System.out.print(currentCell.getStringCellValue() + " | ");
} else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
System.out.print(currentCell.getNumericCellValue() + "| ");
} else if (currentCell.getCellTypeEnum() == CellType.BOOLEAN) {
System.out.println(currentCell.getBooleanCellValue() + " | ");
}
}
来源:https://stackoverflow.com/questions/12382024/how-to-delete-blank-rows-in-between-the-sheet-using-poi