仅在Excel Interop中获取一个列的UsedRange

使用Microsoft的Excel Interop我正在阅读电子表格。 我没有问题得到整个工作表的使用范围,但我想获得只用于一列的行数。 这是我的工作表的一个例子:

在这里输入图像说明

正如你所看到的,列A的使用范围只有3行,而列B是5行。 当我使用我目前的代码:

int rows = sheet.UsedRange.Rows.Count; 

总是返回“5”。 我如何指定我只想要一个单元格的使用范围?

在Excel中UsedRange适用于工作表而不是单个列。 看到这里 。 你可以使用这样的东西得到特定列的最后一行:

 With yourExcelSheet lrow = .Cells(.Rows.Count, lrCol).End(Excel.XlDirection.xlUp).Row End With 

“yourExcelSheet”是工作表,需要声明/分配,“lrow”是你需要的最后一行,“lrcol”是列号(A = 1,B = 2等)

Apols,但这个片段是从vb.net/vba派生的,而不是c#,所以你将需要处理任何所需的转换; 但认为这可能有帮助。

为了得到列A中使用的单元格,您可以尝试这种方法

 // Get the last cell used in the Column A var lastCell = sheet.Range["A:A"].SpecialCells( Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell ) // get the lastColumn used int lastcolumn = lastCell.column; // get the lastRow used int lastRow = lastCell.Row;