poi读取Excel,怎么判断这个单元格是否是合并,

2024-12-13 09:12:05
推荐回答(2个)
回答1:

//判断表中是否含有合并单元格
public boolean hasMerged() {
return sheet.getNumMergedRegions() > 0 ? true : false;
}

// 判断指定区域内是否含有合并单元格
public boolean hasMerged(Region region) {
for (int row = region.getRowFrom(); row < region.getRowTo(); row++) {
for (short col = region.getColumnFrom(); col < region.getColumnTo(); col++){
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
Region r = sheet.getMergedRegionAt(i);
if (r.contains(row, col)) {
return true;
}
}
}
}
return false;
}

回答2:

//poi-3.7.jar
/**
* 合并单元格处理--加入list
*
* @param sheet
* @return
*/
public void getCombineCell(HSSFSheet sheet, List list) {
// 获得一个 sheet 中合并单元格的数量
int sheetmergerCount = sheet.getNumMergedRegions();
// 遍历合并单元格
for (int i = 0; i < sheetmergerCount; i++) {
// 获得合并单元格加入list中
CellRangeAddress ca = sheet.getMergedRegion(i);
list.add(ca);
}
}

/**
* 判断单元格是否为合并单元格
*
* @param listCombineCell
* 存放合并单元格的list
* @param cell
* 需要判断的单元格
* @param sheet
* sheet
* @return
*/
public static Boolean isCombineCell(List listCombineCell,
HSSFCell cell, HSSFSheet sheet) {
int firstC = 0;
int lastC = 0;
int firstR = 0;
int lastR = 0;
for (CellRangeAddress ca : listCombineCell) {
// 获得合并单元格的起始行, 结束行, 起始列, 结束列
firstC = ca.getFirstColumn();
lastC = ca.getLastColumn();
firstR = ca.getFirstRow();
lastR = ca.getLastRow();
if (cell.getColumnIndex() <= lastC&& cell.getColumnIndex()>= firstC) {
if (cell.getRowIndex() <= lastR && cell.getRowIndex() >= firstR) {
return true;
}
}
}
return false;
}
}