C# Excel 互操作计数可见行

C# Excel Interop count visible rows

如何获取可见行的总数?

我尝试了以下方法:
1)

Excel.Range range;
range = ws.UsedRange;

int rCnt = 0;
rCnt = range.Rows.Count;

rCnt = 1执行后

2)

var countRows = ws.Rows.Count;

countRows = 1048576执行后

rCntcountRows 都会 return 31 -> 可见的总行数

使用VisibleRange

Returns a Range object that represents the range of cells that are visible in the window or pane. If a column or row is partially visible, it's included in the range.

例如定义

var xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
    Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
    return;
}
xlApp.Visible = true;

var wb = xlApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
var ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];

那你就可以了

var test = xlApp.ActiveWindow.VisibleRange.Rows.Count;