使用EPPLus获取合并的单元格区域 [英] Get Merged Cell Area with EPPLus
问题描述
我正在使用 EPPlus 来读取Excel文件。
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?
例如:
假设范围(
给定范围 B1,它的Merge属性为true,但是没有办法通过给定范围来获得合并范围单个单元格。
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.
如何获得合并范围?
我希望有一个.MergedRange return Range( A1:C1)
I was hoping for a .MergedRange which would return Range("A1:C1")
推荐答案
没有这样的属性,但工作表中有 MergedCells
属性,该数组包含工作表中所有合并的单元格地址的数组,以及一个 GetMergeCellId()
方法,该索引将为您提供索引给定单元地址。
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)
这篇关于使用EPPLus获取合并的单元格区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!