/**
* 对指定列,如果相邻的cell单元格值相同,则向下合并
*
* @param sheet
* @param startRowIndex 开始行索引
* @param columIndex 指定列索引
* @throws Exception
*/
public void mergeCellsByColumIndex(Sheet sheet,int startRowIndex,int columIndex) {
try {
//创建一个映射,用于存储每个单元格的值及其对应的行索引列表
Map<String, Integer> cellValues = new HashMap<>();
int rows = sheet.getPhysicalNumberOfRows();
for(int rowIndex = startRowIndex ;rowIndex < rows; rowIndex++)
{
Row row = ExcelUtil.getRow(sheet,rowIndex);
Cell cell = row.getCell(columIndex);
if (cell != null) {
String cellValue = cell.getStringCellValue();
if (!cellValues.containsKey(cellValue)) {
cellValues.put(cellValue, rowIndex);
} else {
int firstRowIndex = cellValues.get(cellValue);
//cell不能与已经合并过的cell进行合并,先拆分
removeMergedRegion(sheet,firstRowIndex,rowIndex,columIndex,columIndex);
// 如果已经存在相同的值,则合并单元格
sheet.addMergedRegion(new CellRangeAddress(firstRowIndex, rowIndex, columIndex, columIndex));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 拆分一个区域内的所有合并单元格(一个区域,合并的单元格得全部在这个区域内,待整理一个不是ALL In区域的拆分API)
*
* @param sheet
* @param cellRowStart 区域开始行
* @param cellRowEnd 区域结束行
* @param cellColStart 区域开始列
* @param cellColEnd 区域结束列
* @throws Exception
*/
public static void removeMergedRegion(Sheet sheet, int cellRowStart, int cellRowEnd, int cellColStart,
int cellColEnd) throws Exception {
for (int i = sheet.getNumMergedRegions() - 1; i >= 0; i--) {
CellRangeAddress region = sheet.getMergedRegion(i);
int intFirstRow = region.getFirstRow(); // 合并单元格CELL起始行
int intFirstCol = region.getFirstColumn(); // 合并单元格CELL起始列
int intLastRow = region.getLastRow(); // 合并单元格CELL结束行
int intLastCol = region.getLastColumn(); // 合并单元格CELL结束列
// 判断合并单元格是在区域里面
if (intFirstRow >= cellRowStart && intLastRow <= cellRowEnd && intFirstCol >= cellColStart
&& intLastCol <= cellColEnd) {
Row firstRow = sheet.getRow(region.getFirstRow());
Cell firstCellOfFirstRow = firstRow.getCell(region.getFirstColumn());
sheet.removeMergedRegion(i);
}
}
}
基于Apache POI库,对excel指定列,如果相邻的cell单元格值相同,则向下合并
于 2024-08-16 15:43:25 首次发布