poi删除含有合并单元格的行
List<Integer> needDeleteRowNumList = new ArrayList<>();
needDeleteRowNumList.add(rowNum_SQHJ);
needDeleteRowNumList.add(rowNum_ZZS);
// https://blog.csdn.net/qq_40408317/article/details/118086862
if(CollectionUtil.isNotEmpty(needDeleteRowNumList)) {
// 删除多余的行
for (Integer needDeleteRowNum : needDeleteRowNumList) {
//循环去除 合并单元格 https://blog.csdn.net/qq_40711092/article/details/125055410
for (int i = 0; i < sheet.getRow(needDeleteRowNum).getPhysicalNumberOfCells(); i++) {
removeMergedRegion(sheet, needDeleteRowNum, i);
}
// 清除行内容
sheet.removeRow(sheet.getRow(needDeleteRowNum));
}
//上移行
needDeleteRowNumList.sort(Integer::compareTo);
int rowNum = sheet.getLastRowNum();
for (int i = 0; i < needDeleteRowNumList.size(); i++) {
Integer integer = needDeleteRowNumList.get(i);
Integer num = integer + 1 - i;
// 向上移动行时需要先去除合并单元格
sheet.shiftRows(num, rowNum, -1);
}
}
// 参数1:sheet、参数2:开始行、参数3:开始列
public static void removeMergedRegion(Sheet sheet, int row , int column)
{
int sheetMergeCount = sheet.getNumMergedRegions();//获取所有的单元格
int index = 0;//用于保存要移除的那个单元格序号
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress ca = sheet.getMergedRegion(i); //获取第i个单元格
int firstColumn = ca.getFirstColumn();
int lastColumn = ca.getLastColumn();
int firstRow = ca.getFirstRow();
int lastRow = ca.getLastRow();
if(row >= firstRow && row <= lastRow)
{
if(column >= firstColumn && column <= lastColumn)
{
index = i;
}
}
}
if(index > 0) {
sheet.removeMergedRegion(index);//移除合并单元格
// System.out.println("移除合并单元格:" + index);
}
}