Apache Poi excel 删除空白行

excel

1个回答

写回答

Guokaichen0123

2025-06-19 14:50

+ 关注

excel
excel

如何使用Apache Poi删除excel中的空白行

Apache Poi是一个流行的Java库,用于处理Microsoft Office格式的文件。它提供了一组功能强大的API,使我们能够读取、写入和修改excel文件。在处理excel文件时,经常会遇到删除空白行的需求。本文将介绍如何使用Apache Poi来删除excel中的空白行,并提供案例代码。

步骤1:导入Apache Poi库

首先,我们需要导入Apache Poi库到我们的项目中。可以从官方网站(https://poi.apache.org/)下载最新版本的Apache Poi库,然后将相关的JAR文件添加到项目的类路径中。

步骤2:创建excel文件并读取数据

在开始删除空白行之前,我们需要先创建一个excel文件并读取其中的数据。下面是一个简单的示例代码:

Java

// 导入必要的类

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

// 创建工作簿和工作表

Workbook workbook = new XSSFWorkbook();

Sheet sheet = workbook.createSheet("Sheet1");

// 创建行和单元格

Row row1 = sheet.createRow(0);

Cell cell1 = row1.createCell(0);

cell1.setcellValue("姓名");

Row row2 = sheet.createRow(1);

Cell cell2 = row2.createCell(0);

cell2.setcellValue("张三");

Row row3 = sheet.createRow(2);

Cell cell3 = row3.createCell(0);

cell3.setcellValue("");

// 保存excel文件

try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {

workbook.write(outputStream);

} catch (IOException e) {

e.printStackTrace();

}

// 读取excel文件

try (FileInputStream inputStream = new FileInputStream("example.xlsx")) {

Workbook workbook = WorkbookFactory.create(inputStream);

Sheet sheet = workbook.getSheetAt(0);

// 迭代每一行并输出数据

for (Row row : sheet) {

Cell cell = row.getcell(0);

System.out.println(cell.getStringCellValue());

}

} catch (IOException | InvalidFormatException e) {

e.printStackTrace();

}

在上述代码中,我们创建了一个名为"example.xlsx"的excel文件,并在第一列中添加了一些数据。然后我们读取该文件,并迭代每一行并输出数据。

步骤3:删除空白行

现在我们已经有了excel文件的数据,接下来我们将使用Apache Poi来删除其中的空白行。下面是一个删除空白行的示例代码:

Java

// 导入必要的类

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

// 读取excel文件

try (FileInputStream inputStream = new FileInputStream("example.xlsx")) {

Workbook workbook = WorkbookFactory.create(inputStream);

Sheet sheet = workbook.getSheetAt(0);

// 迭代每一行并删除空白行

for (int i = sheet.getLastRowNum(); i >= 0; i--) {

Row row = sheet.getRow(i);

Cell cell = row.getcell(0);

if (cell == null || cell.getStringCellValue().isEmpty()) {

sheet.removeRow(row);

}

}

// 保存excel文件

try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {

workbook.write(outputStream);

} catch (IOException e) {

e.printStackTrace();

}

} catch (IOException | InvalidFormatException e) {

e.printStackTrace();

}

在上述代码中,我们首先读取了之前创建的excel文件。然后,我们从最后一行开始迭代每一行,并检查第一列的单元格是否为空。如果为空,则删除该行。最后,我们保存了修改后的excel文件。

本文介绍了如何使用Apache Poi来删除excel中的空白行。首先,我们导入了Apache Poi库并创建了一个excel文件,然后读取了其中的数据。接着,我们使用迭代的方式删除了空白行,并保存了修改后的excel文件。希望这篇文章能帮助你在使用Apache Poi处理excel文件时解决删除空白行的问题。

参考资料:

1. Apache Poi官方网站:https://poi.apache.org/

2. Apache Poi GitHub仓库:https://github.com/apache/poi

举报有用(4)分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号