java读取excel,将空行上移
改造前:
效果图:
上代码:
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 RemoveEmptyRows {
public static void main(String[] args) {
// 设置Excel文件路径
String excelFilePath = "C:\\Users\\17315\\Desktop\\newFolder\\合并单元格.xlsx";
// 读取Excel文件
try (FileInputStream fis = new FileInputStream(excelFilePath);
Workbook workbook = new XSSFWorkbook(fis)) {
// 获取第一个工作表
Sheet sheet = workbook.getSheetAt(0);
String remarkValue = "";
String remarkNextValue = "";
String remarkValue1 = "";
String remarkNextValue1 = "";
String remarkValue2 = "";
// 循环遍历行,从最后一行开始
for (int rowIndex = sheet.getLastRowNum(); rowIndex >= 0; rowIndex--) {
Row row = sheet.getRow(rowIndex);
if(row==null){
sheet.shiftRows(rowIndex+1 , sheet.getLastRowNum(), -1);
}else {
// 获取A列的单元格
if (row.getCell(0) == null) {
if(row.getCell(5)!=null){
Row remarkRow = sheet.getRow(rowIndex-1);
remarkValue1 = remarkValue.concat(remarkRow.getCell(5).getStringCellValue() + "|");
remarkNextValue1 = remarkNextValue.concat(row.getCell(5).getStringCellValue());
remarkValue2 = remarkValue1.concat(remarkNextValue1);
Cell remarkCell = remarkRow.createCell(5);
remarkCell.setCellValue(remarkValue2.toString());
System.out.println("remarkCell " + remarkValue2);
}
// 如果A列单元格为空,删除该行
//sheet.removeRow(row);
// 移动删除行上方的行,使单元格连续
sheet.shiftRows(rowIndex+1 , sheet.getLastRowNum(), -1);
} else {
// 如果A列单元格不为空,结束循环
continue;
}
}
}
// 保存修改后的Excel文件
try (FileOutputStream fos = new FileOutputStream(excelFilePath)) {
workbook.write(fos);
}
System.out.println("删除空行并将下方行上移成功。");
} catch (IOException e) {
e.printStackTrace();
}
}
}
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>5.2.3</version>
</dependency>
tips:poi版本4.0.1以下shiftRows方法,移动单元格缺少复制下部单元格,此处建议使用4.1.2之上版本