What is the analogue to Excel Interop's Worksh

2019-05-30 05:58发布

问题:

Using Excel Interop, you can get the count of rows in use by a sheet like so:

_xlSheet.UsedRange.Rows

(where "_xlSheet" is an Excel.Worksheet).

What is the equivalent in Spreadsheet Light?

You can add a worksheet like so:

var sl = new SLDocument();
. . .
sl.AddWorksheet("SheetsToTheWind");

...but how can you then access that worksheet to interrogate it for its used row count?

回答1:

After adding the worksheet it is active as well. That means that you can get the WorksheetStatistics from the method GetWorksheetStatistics. That statistics instance has a NumberOfRows property:

// NOTE: The information is only current at point of retrieval. 
var stats = sl.GetWorksheetStatistics();
var rowcount = stats.NumberOfRows;

If you want to to know the rowcount of all sheets you can do:

foreach(var name in sl.GetSheetNames())
{
    sl.SelectWorksheet(name);
    var stats = sl.GetWorksheetStatistics();
    var rowcount = stats.NumberOfRows;    
    Trace.WriteLine(String.Format("sheet '{0}' has {1} rows", name, rowcount));
}


回答2:

Adding to rene's answer:

Since accessing the Statistics' NumberOfRows property does not automagically update (you must call GetWorksheetStatistics() each time to get the up-to-date stats), I found it handy to write this helper method:

private int GetCurrentNumberOfRows()
{
    // This reference to "sl" assumes that you have declared "SLDocument sl;" and
    // instantiated it ("sl = new SLDocument();"), perhaps in your class' constructor
    var stats = sl.GetWorksheetStatistics();
    return stats.NumberOfRows;
}

..and then call it as needed:

int lastRow = GetCurrentNumberOfRows();