[英]How do I get the size of a merged Excel cell
I'm trying to write code in C# to parse a large Excel sheet that wasn't really designed with automation in mind, and it's full of merged cells. 我正在尝试用C#编写代码来解析一个大型Excel工作表,该工作表并非真正出于自动化目的而设计的,它充满了合并的单元格。 Many times I know the location of one cell, but need to get the text of another cell a few cells away, but those cells may be merged and span multiple normal cells.
很多时候,我知道一个单元格的位置,但是需要将另一个单元格的文本移到几个单元格之外,但是这些单元格可能会合并并跨越多个普通单元格。 How do I get the size of a merged cell in number of cells?
如何获得合并单元的数量(以单元数为单位)?
Also, how can I get the location of a cell a certain number of cells away, when the cells in between are merged? 另外,合并之间的单元格时,如何将某个单元格的位置移开一定数量的单元格? I tried Excel.Range.Offset, but that seems to be only counting real cells, not merged ones (so if there's a 4-wide merged cell in between, offset 2 will take me to the middle of that cell, rather than the one next to it).
我尝试了Excel.Range.Offset,但是那似乎只是在计算真实单元格,而不是合并单元格(因此,如果之间有一个4宽的合并单元格,则偏移量2会将我带到该单元格的中间,而不是其中一个在它的旁边)。
You can use the following code to determine size of merged area: 您可以使用以下代码来确定合并区域的大小:
var activeSheet = this.Application.ActiveSheet as Excel.Worksheet;
if (activeSheet != null)
{
var activeCell = activeSheet.Cells[2, 2];
if (activeCell.MergeCells)
{
if (activeCell.MergeArea != null)
{
dynamic mergeAreaValue2 = activeCell.MergeArea.Value2;
object[,] vals = mergeAreaValue2 as object[,];
if (vals != null)
{
int rows = vals.GetLength(0);
int cols = vals.GetLength(1);
}
}
}
}
Assumption is that Cells[2,2]
is left upper corner of merged area. 假设
Cells[2,2]
位于合并区域的左上角。 In variables rows and cols will be the amount of rows and columns in merged area - so this is an answer to the question how many rows or columns should be skipped. 在变量中,row和cols将是合并区域中行和列的数量-因此,这是对应跳过多少行或列的问题的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.