Search code examples
c#coordinatesepplus

Convert Address Reference Style A1 to Style R1C1 in EPPlus


I am using this library with C#. I have as input coordinates in the [LetterNumber] form. But then I have to work on the with iterators. Therefore I'd need to transform them in the [Number,Number] system.

Eg. B5--->2,5 and back

and back. It might be simple for cells near the origin but more complicated for cells like AB23. What's more it could be A23 or AB23 so it's hard to tell. I can't believe there's nothing built in. I know that easy working with row, column. The conundrum comes getting as input the other coordinate system. Thank you


Solution

  • I think the closest you will get to something built in are the static methods in ExcelCellBase like this:

    Console.WriteLine(ExcelCellBase.TranslateToR1C1("AB23", 0, 0)); //Prints "R[23]C[28]"
    Console.WriteLine(ExcelCellBase.TranslateFromR1C1("R23C28", 0, 0)); //Prints "$AB$23"
    

    But if you prefer a simpler output you could kind of fake it like this:

    var addr = new ExcelAddress("AB23");
    Console.WriteLine($"{addr.Start.Row},{addr.Start.Column}");  //Prints "23,28"
    
    addr = new ExcelAddress(23, 28, 23, 28);
    Console.WriteLine(addr.Address);  //Prints "AB23"
    

    But if you are looking to iterate over a range say you can do something like this:

    addr = new ExcelAddress("A10:AB23");
    var s = addr.Start;
    var e = addr.End;
    Console.WriteLine($"Rows={e.Row - s.Row} Cols={e.Column - s.Column}");  //Prints "Rows=13 Cols=27"
    

    Lots of ways you can do it.