java删除excel行
时间: 2023-08-22 14:06:03 浏览: 87
要在Java中删除Excel行,同样可以使用Apache POI库。下面是一个简单的示例代码:
```java
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class DeleteExcelRowExample {
public static void main(String[] args) throws IOException {
// 创建工作簿
Workbook workbook = WorkbookFactory.create(new File("example.xlsx"));
// 获取工作表
Sheet sheet = workbook.getSheetAt(0);
// 删除第3行
deleteRow(sheet, 2);
// 保存工作簿
FileOutputStream outputStream = new FileOutputStream("example.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
}
// 删除指定行
private static void deleteRow(Sheet sheet, int rowIndex) {
Row row = sheet.getRow(rowIndex);
if (row != null) {
sheet.removeRow(row);
// 移动下方行
int lastRowNum = sheet.getLastRowNum();
if (rowIndex != lastRowNum) {
sheet.shiftRows(rowIndex + 1, lastRowNum, -1);
}
}
}
}
```
在这个示例代码中,我们首先使用WorkbookFactory创建了一个工作簿,然后获取了第一个工作表。接着,我们调用deleteRow方法,传入要删除的行的索引。deleteRow方法会移除指定行的行对象,并将下方的行向上移动。最后,我们将修改后的工作簿保存到磁盘上。
阅读全文
相关推荐

















