Search code examples
c#excelepplus

Use EPPlus to translate the location of the Excel Cell


I am new to using EPPlus.

I want to adress a cell, relative to a starting point, what is the best way to achieve this?

E.g:

var startLocation = "C5";
var newLocation1 = TLoc(startLocation, 2, 3); //E8
var newLocation2 = TLoc(startLocation, 0, 1); //C6

For now I wrote this method myself, because I am unfamiliar with EPPlus functionality:

/// <summary>
/// Use EPPlus to translate the Location.
/// </summary>
/// <param name="startLocation"></param>
/// <param name="columns"></param>
/// <param name="rows"></param>
/// <returns></returns>
private string TLoc(string startLocation, int columns, int rows)
{
    using (ExcelPackage tmpPack = new ExcelPackage())
    {
        var tmpWs = tmpPack.Workbook.Worksheets.Add("temp");
        var startCell = tmpWs.Cells[startLocation];

        int startColumn = startCell.Start.Column;
        int startRow = startCell.Start.Row;

        int tColumn = startColumn + columns;
        int tRow = startRow + rows;

        ExcelAddress translatedAddress = new ExcelAddress(tRow, tColumn, tRow, tColumn);

        return translatedAddress.ToString();
    }
}

Please show me an example or link me to documentation. Thank you!

To be more specific: examples of using EPPlus to achieve this functionality.

I like to use proven technology when available instead of risking the introduction of new bugs.


Solution

  • For an EPPlus specific solution, the only way I can think of that is "shortest" is something like this:

    //Prints "E8"
    Console.WriteLine(ExcelCellBase.TranslateFromR1C1(ExcelCellBase.TranslateToR1C1("C5", -3, -2), 0, 0)); 
    
    //Prints "C8"
    Console.WriteLine(ExcelCellBase.TranslateFromR1C1(ExcelCellBase.TranslateToR1C1("C5", -1, 0), 0, 0)); 
    

    Not the cleanest but since they makers of it didnt expose the translate function that backs those two methods we cant use it directly unfortunately.