需要在C#中查找Excel范围的起点和终点
我试图从COM读取从C#中的Excel文件,并可以得到它打开并加载就好了。 但是,我不想使用表单上的所有数据(每月展开一次),只是从表单顶部开始的一个子集(第3行用于标题,第4行用于数据)并且到达结尾。 我现在可以得到一个范围代表整个数据集为Excel.Worksheet.UsedRange
,但接下来我需要或者操纵这个下降到所需的范围,或(最好)find终点进入我的实际数据的另一个范围恢复。 任何人都可以告诉我如何做这两个? 谢谢。
我不知道你在做什么。 但是这里有一些例子。
假设我有以下范围:
Excel.Worksheet sheet = this.Application.ActiveSheet as Excel.Worksheet; Excel.Range range = sheet.get_Range("A1", "B5") as Excel.Range;
把你的范围向下移动n
行:
int n = 1; int rows = range.Rows.Count; int cols = range.Columns.Count; Excel.Range newRange = range.get_Offset(n, 0).get_Resize(rows-n,cols); newRange.Select(); //will select the new range will be 1 row lower
移动你的底部行
Excel.Range newRange = range.get_Resize(rows-n,cols); newRange.Select(); //will select the new range will be 1 row higher
我想你可以弄清楚如何将它左右移动。
get_Offset()
将整个范围移动,然后你需要调整范围的大小。
编辑:现在,我知道你想要什么。
要selectLast Cell:
Excel.Range lastCell = range.Cells[rows, cols] as Excel.Range; lastCell.Select();
现在你可以使用你自己的起点:
Excel.Range newRange = sheet.get_Range("B1", lastCell); newRange.Select();
您应该可以使用Range.Row , Range.Rows.Count , Range.Column和Range.Columns.Count属性来获取您的范围的开始和结束,如下所示:
Dim used As Range, first As Range, last As Range Set used = Sheet1.UsedRange Set first = Sheet1.Cells(used.Row, used.Column) Set last = Sheet1.Cells(used.Row + used.Rows.Count, used.Column + used.Columns.Count) MsgBox ("First: " + first.Address + " Last: " + last.Address)
该示例代码在VBA中,但是所有这些函数都应该可以在COM中使用C#。
来自MSDN :
“使用End属性以及来自XlDirection枚举(xlUp,xlToRight,xlToLeft,xlDown)的值来检索代表该区域末尾的单元格的区域,就好像您已经按下了由列举值;“
rngDown = rng.get_End(Excel.XlDirection.xlDown);
好的,find了答案(经过近3个小时的总search,在这里问了2个小时),所以会在这里发布给别人。
Excel.Range urange = (Excel.Range)xlWorkSheet.UsedRange; // gives us the actual range
string used = urange.get_Address(false, false, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing));
从MSDN:
public string get_Address (
[OptionalAttribute] Object RowAbsolute,
[OptionalAttribute] Object ColumnAbsolute,
[OptionalAttribute] XlReferenceStyle ReferenceStyle,
[OptionalAttribute] Object External,
[OptionalAttribute] Object RelativeTo
)
这显然是前两个是真/假标志,下一个被定义为一个Microsoft.Office.Interop.Excel.XlReferenceStyle
对象,我猜测外部是要么是外部文件的引用,要么是某种标志。 相对而言,我只能猜测它指的是一个任意定义的位置,也许是一个范围对象,也许是一个string。 不幸的是,MSDN在这个主题上是非常稀疏的,所以我只是在这里猜测和张贴我的猜测。 然而,使用这个代码,因为我已经发布,我能够检索总是用作“A1:B245”,这给我正是我想要的,然后我可以通过提取第二部分创build一个新的范围,然后可以继续。