1:
/** * Created by liuguangxin on 2018/5/16. * <p> * MergeRegion:表示excel中cell的信息,startRow与endRow表示当前cell的起始与结束行编号(base 1), * startCol与endCol同理表示列的起始与结束列编号(base 1)<p/> */ public class MergeRegion { @Override public String toString() { return "[ " + "merged=" + merged + ", startRow=" + startRow + ", endRow=" + endRow + ", startCol=" + startCol + ", endCol=" + endCol + "] "; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MergeRegion result = (MergeRegion) o; if (merged != result.merged) return false; if (startRow != result.startRow) return false; if (endRow != result.endRow) return false; if (startCol != result.startCol) return false; return endCol == result.endCol; } @Override public int hashCode() { int result = (merged ? 1 : 0); result = 31 * result + startRow; result = 31 * result + endRow; result = 31 * result + startCol; result = 31 * result + endCol; return result; } public boolean merged; public int startRow; public int endRow; public int startCol; public int endCol; public MergeRegion(boolean merged, int startRow, int endRow , int startCol, int endCol) { this.merged = merged; this.startRow = startRow; this.endRow = endRow; this.startCol = startCol; this.endCol = endCol; } }
获取单元格的之,包含是否是合并的情况:
/** * @param sheet * @param rowIndex * @param columnIndex * @return 返回指定cell对应的值,否则返回null */ public static String getCellValue(Sheet sheet, int rowIndex, int columnIndex) { MergeRegion region = isMergedRegion(sheet, rowIndex, columnIndex); if (region.merged) { // |—————————————————————— // | | | | // |—————————————————————— // | | | | // |—————————————————————— // | | | | // |—————————————————————— // 对于如上3*3的表格合并之后,只有获取相对3*3表格内 (0,0)的位置才会获取到数据, // 因此对于如果获取的是合并cell的值的话需要转换rowIndex,columnIndex为相对表格内的(0,0)处 rowIndex = region.startRow - 1; columnIndex = region.startCol - 1; } Row row = sheet.getRow(rowIndex); Cell cell; if (Objects.nonNull(row) && (cell = row.getCell(columnIndex)) != null) { cell.setCellType(CellType.STRING); return deleteEnterChar(cell.getStringCellValue()); } return null; }