File file = new File("path/to/excel/file.xlsx"); Workbook workbook = WorkbookFactory.create(file);
Sheet sheet = workbook.getSheet("sheetName");
int startRow = 1; // 第二行(第一行是标题) int endRow = sheet.getLastRowNum(); int startColIndex = sheet.getRow(0).getCell(1).getColumnIndex(); // B列 int endColIndex = sheet.getRow(0).getCell(2).getColumnIndex(); // C列
for (int rowNum = startRow; rowNum <= endRow; rowNum++) { Row row = sheet.getRow(rowNum); boolean isEmpty = true; for (int colIndex = startColIndex; colIndex <= endColIndex; colIndex++) { Cell cell = row.getCell(colIndex, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL); if (cell != null && cell.getCellType() != CellType.BLANK) { isEmpty = false; break; } } if (isEmpty) { sheet.removeRow(row); } }
FileOutputStream outputStream = new FileOutputStream("path/to/modified/excel/file.xlsx"); workbook.write(outputStream); workbook.close(); outputStream.close();