获取Excel范围对象的最后一个单元格(列、行)

7
我有一个Microsoft.Office.Interop.Excel.Range对象,想要估计该范围的结束坐标即(最后一列,最后一行)。
没有像LastColLastRow这样的属性。唯一的属性是ColumnRow,它们指定了第一个单元格。但我如何获取范围的最后一个单元格呢?

1
Columns.Count,Rows.Count - user2140261
1
Columns.Count和Rows.Count适用于连续的范围。对于非连续范围(例如“D1:E3,A1:B3”),您需要使用Areas属性。 - Joe
3个回答

10
这可以有两种方法:
  1. 使用 Worksheet.UsedRange 确定范围。这将给您一个类似于 A1:F10 的区域,或使用 Worksheet.UsedRange.SpecialCells(IExcel.XlCellType.xlCellTypeLastCell) 获取 F10

  2. 使用 Range.End[IExcel.XlDirection] 属性,它返回指定方向上最后一个连续的非空单元格。请注意,如果该范围为空,则会返回给定方向上的第一个非空单元格或最后一个单元格(当 Excel 达到其边界时)。例如:整个列 A 都是空的,Range["A1"].End[IExcel.XlDirection.xlDown] 将是 A65535(Excel 97-2003 中的最后一行,Excel 2007 中为 A1048576)。

//如果您想知道 IExcel 是什么,可以参考以下代码
using IExcel = Microsoft.Office.Interop.Excel;


7

这将获取范围的第一个和最后一个单元格:

  1. Initiate Excel.

  2. Open workbook.

  3. Select your range, in this case I got the used range of the active sheet.

  4. Call the get_address method of the range.

  5. Split the result of get_address on the colon.

  6. The first value of the array resulting from the split will have the beginning cell.

  7. The second value of the array resulting from the split will have the ending cell.

  8. Replace the dollar signs with nothing and you will have the beginning and ending cells for the range.

    Microsoft.Office.Interop.Excel.Application excel = new Application();
    Microsoft.Office.Interop.Excel.Workbook workBook =
        excel.Workbooks.Open(fileLocation);
    Microsoft.Office.Interop.Excel.Worksheet sheet = workBook.ActiveSheet;
    Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
    string address = range.get_Address();
    string[] cells = address.Split(new char[] {':'});
    string beginCell = cells[0].Replace("$", "");
    string endCell = cells[1].Replace("$", "");
    workBook.Close(true);
    excel.Quit();
    
如果您想要相对于范围的起始位置获取最后一列和最后一行,则可以按照以下步骤进行操作:
    int lastColumn = range.Columns.Count;
    int lastRow = range.Rows.Count;

0

使用Excel 2013,我们遇到了很多情况,其中UsedRangexlCellTypeLastCell会给出非常错误的值。

例如,我们可能有一个仅包含7列的工作表,但有时这两个函数会告诉我们的C#代码有16,000多列的数据。

我发现唯一真正有效的方法是使用此建议中的提示来找到包含数据的右下角单元格:

sheet.Cells.Find()


1
我也遇到了这个问题。值似乎相差很大,因为.SpecialCells(XlCellType.xlCellTypeLastCell)返回的是工作表对象UsedRange属性的最后一个“使用”单元格,而不是调用它的Range对象的最后一个单元格。 - TheAtomicOption

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接