没有这样的属性开箱即用,但工作表有一个MergedCells属性,其中包含工作表中所有合并单元格地址的数组,以及一个GetMergeCellId()方法,它将为您提供给定单元格地址的索引.
因此,我们可以将这些组合成一个可用于获取地址的小扩展方法.像这样的东西:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用如下:
using (var excel = new ExcelPackage(new FileInfo("inputFile.xlsx")))
{
var ws = excel.Workbook.Worksheets["sheet1"];
var b3address = ws.Cells["B3"].GetMergedRangeAddress();
}
Run Code Online (Sandbox Code Playgroud)
(请注意,如果您在多单元格范围内使用此方法,它将仅返回范围中第一个单元格的合并单元格地址)
您可以从工作表中获取所有合并的单元格,因此您可以使用以下命令找到特定单元格所属的合并范围:
public string GetMergedRange(ExcelWorksheet worksheet, string cellAddress)
{
ExcelWorksheet.MergeCellsCollection mergedCells = worksheet.MergedCells;
foreach (var merged in mergedCells)
{
ExcelRange range = worksheet.Cells[merged];
ExcelCellAddress cell = new ExcelCellAddress(cellAddress);
if (range.Start.Row<=cell.Row && range.Start.Column <= cell.Column)
{
if (range.End.Row >= cell.Row && range.End.Column >= cell.Column)
{
return merged.ToString();
}
}
}
return "";
}
Run Code Online (Sandbox Code Playgroud)
更新:
事实证明,使用 EPPLUS 有更简单的方法,只需执行以下操作:
var mergedadress = worksheet.MergedCells[row, column];
Run Code Online (Sandbox Code Playgroud)
例如,如果 B1 在合并范围“A1:C1”中:
var mergedadress = worksheet.MergedCells[1, 2]; //value of mergedadress will be "A1:C1".
Run Code Online (Sandbox Code Playgroud)
2 是列号,因为 B 是第二列。
| 归档时间: |
|
| 查看次数: |
5308 次 |
| 最近记录: |