简体   繁体   中英

C# ExcelDNA read from dynamic array

My first time posting here. Ordinarily I find everything one could possibly need already answered. In this case, for the life of me I cannot figure this out, so here goes.

I have a range of values in excel that I am attempting to read using ExcelDNA. This range will always have 2 columns, but the number of rows is dynamic as follows:

n-number of rows

String, float String, float ... row n

Now I can read a range using ExcelDNA and ExcelReference as follows:

object[,] bencharray = ExcelData.ReadArrayValue(0, 10, 0, 1, "Sheet1");


    public static class ExcelData
{
            public static dynamic ReadArrayValue(int rf, int rl, int cf, int cl, string sheet)
        {
            //This reads an array with 4 co-ordinates from the specified sheet
            ExcelReference readarray = new ExcelReference(rf, rl, cf, cl, sheet);
            return readarray.GetValue();
        }
}

So this will staticly read an 11 row range with 2 columns starting from cell A1.

What I'm looking for is something similar to VBA's xlDown or UsedRange. Ideally this would stop when the bottom of the range is blank and allow cells further down the sheet to still be used.

I'm not sure if I should be using Interop.Excel or how to use this.

Any help would be appreciated. Many Thanks

You can do it with the C API. You need the xlcSelectEnd function, which extends the selection in one of the directions. So you'd call

XlCall.Excel(XlCall.xlcSelectEnd, 4);

where the directions are:

  • 1 - Left
  • 2 - Right
  • 3 - Up
  • 4 - Down

This means you'll have to set a selection ( xlcSelect ), then extend it ( xlcSelectEnd ), then get the current selection ( xlfSelection ).

This discussion on the Google group might be useful too: https://groups.google.com/group/exceldna/browse_frm/thread/cc87114539c78f53 .

All of this sounds a bit complicated, and makes me think you should also consider the COM API.

Using Govert's sample ExcelSelectionHelper, you could do something like this:

Given enums of:

public enum DirectionType
{
    Up = 3,
    ToRight = 2,
    Down = 4,
    ToLeft = 1
}

You could so something like this:

public static ExcelReference End( this ExcelReference reference, DirectionType direction )
{
    ExcelReference end = null;

    using ( new ExcelSelectionHelper( reference ) )
    {
        // myReference is selected now...
        XlCall.Excel( XlCall.xlcSelectEnd, (int)direction );

        var selection = XlCall.Excel( XlCall.xlfSelection ) as ExcelReference;
        var row = selection.RowFirst;
        var col = selection.ColumnFirst;

        end = new ExcelReference( row, row, col, col, selection.SheetId );
    }

    return end;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM