0%

POI读取合并单元格内容

POI读取合并单元格内容

产品们想到的excel真是千奇百怪,这次又遇到一个读取包含合并单元格的excel文件,一开始直接读取,直接报空了,没办法,只能对于这些列进行判断是否为合并单元格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private boolean isMergedRegion(Sheet sheet, int row, int column) {
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress range = sheet.getMergedRegion(i);
int firstColumn = range.getFirstColumn();
int lastColumn = range.getLastColumn();
int firstRow = range.getFirstRow();
int lastRow = range.getLastRow();
if (row >= firstRow && row <= lastRow) {
if (column >= firstColumn && column <= lastColumn) {
return true;
}
}
}
return false;
}

如果是合并单元格的话,使用单独的方法来进行读取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public String getMergedRegionValue(Sheet sheet, int row, int column) {
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress ca = sheet.getMergedRegion(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) {
Row fRow = sheet.getRow(firstRow);
Cell fCell = fRow.getCell(firstColumn,Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
return fCell.toString();
}
}
}

return null;
}

欢迎关注我的其它发布渠道