import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class RemoveEmptyRowsFromExcel {
public static void main(String[] args) {
String filePath = "D:\\a.xlsx";
try (FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(fis)) {
Sheet sheet = workbook.getSheetAt(0);
for (int i = sheet.getLastRowNum(); i >= 0; i--) {
Row row = sheet.getRow(i);
boolean isEmptyRow = true;
if (row != null) {
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if (cell != null && cell.getCellType() != CellType.BLANK) {
isEmptyRow = false;
break;
}
}
}
if (isEmptyRow) {
sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
}
}
try (FileOutputStream fos = new FileOutputStream(filePath)) {
workbook.write(fos);
}
System.out.println("空值行已成功删除。");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java中 去除Excel表格中 空格案例
最新推荐文章于 2024-08-27 09:00:00 发布