Search code examples
c#arraysexceloffice-interop

get range in excel interop based on argument


I have a method that takes parameters and based on one parameter I have to get a different range in my excel sheet, for example, if my parameter is '2', then the range would be:

A1 - B1 (2 columns on the top row)

if the parameter is '4' then the range is:

A1 - D1 (4 columns)

the way I thought about it is to make a string array like so:

public void excelExport(int columns) {
 string[] alphabet = { "A", "B", "C", "D" ... "Z"};
 Range range = ws.get_Range("A1", alphabet[columns] + "1");
}

however, excel can go into double,triple etc.. character columns (I doubt I'll need to go into triple character columns 'AAA, AAB etc...') but as you can see, I can't possible make an array that has like 50 indexes because what if I need 51 or 52 columns at some point? my array method will not work.

is there a more basic way of getting ranges dynamically based on the number in the argument?


Solution

  • Add this helper method. It assumes that if columnNumber is set to 1 that this represents column "A". Value 2 represents "B" etc.:

    private string GetExcelColumnName(int columnNumber)
    {
        int dividend = columnNumber;
        string columnName = String.Empty;
        int modulo;
        while (dividend > 0)
        {
            modulo = (dividend - 1) % 26;
            columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
            dividend = (int)((dividend - modulo) / 26);
        } 
        return columnName;
    }
    

    Use it like this:

    public void ExcelExport(int columnNumber)
    {
        Range range = ws.get_Range("A1", GetExcelColumnName(columnNumber) + "1");
        // do stuff with range
    }