Reputation: 43
I'm using NPOI to retrieve data from Excel into a text file. Based on the Excel sheet I'm supposed to show the data in this manner.
The cell for 13/3/19
in the Excel sheet is merged across two rows and I don't know how I can retrieve the merge cell value for May
and display it. Does anyone have any ideas?
Upvotes: 2
Views: 2915
Reputation: 129667
In Excel, if a cell is merged with other cells, the first cell in the merged region is the one that has the actual value. The other cells in the region are blank. The merged regions are kept in the worksheet object, since they can span multiple rows and columns.
To get the value, you need to:
IsMergedCell
property on the cell itself.Here is a helper method I wrote which should do the trick:
public static ICell GetFirstCellInMergedRegionContainingCell(ICell cell)
{
if (cell != null && cell.IsMergedCell)
{
ISheet sheet = cell.Sheet;
for (int i = 0; i < sheet.NumMergedRegions; i++)
{
CellRangeAddress region = sheet.GetMergedRegion(i);
if (region.ContainsRow(cell.RowIndex) &&
region.ContainsColumn(cell.ColumnIndex))
{
IRow row = sheet.GetRow(region.FirstRow);
ICell firstCell = row?.GetCell(region.FirstColumn);
return firstCell;
}
}
return null;
}
return cell;
}
Then as you are looping through your cells you can just call this method for every cell. If the cell is merged, it will return the cell that has the value for that merged region, otherwise it will just return the original cell back. So then you don't have to think about it anymore.
cell = GetFirstCellInMergedRegionContainingCell(cell);
if (cell != null)
{
// get the value
}
Upvotes: 3