I'm using EPPlus to read excel files.
I have a single cell that is part of merged cells. How do I get the merged range that this cell is part of?
For example:
Assume Range ("A1:C1") has been merged.
Given Range "B1" it's Merge property will be true but there isn't a way to get the merged range given a single cell.
How do you get the merged range?
I was hoping for a .MergedRange which would return Range("A1:C1")
Right-click the merged cell B1:D1, select "paste special -> formulas" You should see the merged cell being 0. Type Col1 in the merged cell. You should now see all B2, C2, D2 to be Col1, i.e. now you can reference the merged cell as you expect it to be.
When a group of cells in a row are merged and the text wraps to two or more lines, double-clicking the row border just to the left of column A (or Format>Row>Autofit) auto-heights the row to one line of text. Either of these actions should heighten the row to fit the text in the merged cells.
If you just needed to do it quickly in excel: Highlight all the data, copy it, then right click to paste where you want the data to be, and click "paste special", then finally "transpose" Click this one.
There is no such property out of the box but the worksheet has a MergedCells
property with an array of all the merged cell addresses in the worksheet and a GetMergeCellId()
method which will give you the index for a given cell address.
We can therefore combine these into a little extension method you can use to get the address. Something like this:
public static string GetMergedRangeAddress(this ExcelRange @this)
{
if (@this.Merge)
{
var idx = @this.Worksheet.GetMergeCellId(@this.Start.Row, @this.Start.Column);
return @this.Worksheet.MergedCells[idx-1]; //the array is 0-indexed but the mergeId is 1-indexed...
}
else
{
return @this.Address;
}
}
which you can use as follows:
using (var excel = new ExcelPackage(new FileInfo("inputFile.xlsx")))
{
var ws = excel.Workbook.Worksheets["sheet1"];
var b3address = ws.Cells["B3"].GetMergedRangeAddress();
}
(Note that in the event that you use this method on a multi-celled range it will return the merged cell address for the first cell in the range only)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With