Search code examples
c#csvxlsx

Get .xlsx column name from index in C#


I would like to create a function that will convert a number to .csv file column.

For example:

  • Number 5 -> Column E
  • Number 29 -> Column AB

and so on ..

I've made this function so far:

public class Test
{
    public static string GetColumn(int index)
    {
        StringBuilder col = new StringBuilder();

        const int alpha_count = 26;

        char alpha = (char)64;

        if (index <= alpha_count)
        {
            col.Append(((char)(alpha + index)).ToString());
        }
        else
        {
            // I am stuck here....

        }

        return col.ToString();
    }
    static void Main(string[] args)
    {

        var col = Test.GetColumn(1);

    }
}

I am stuck on the condition if the number exceeds 26 (the length of the alphabet).


Solution

  • I have used this previously and should work as you describe… this came from…

    Convert an Excel column number to a column name or letter:

    Also, unless I am missing something… would not 29 -> AC?

    … 26=Z, 27=AA, 28=AB and 29=AC …

    private static string ColumnIndexToColumnLetter(int colIndex) {
      int div = colIndex;
      string colLetter = String.Empty;
      int mod = 0;
      while (div > 0) {
        mod = (div - 1) % 26;
        colLetter = (char)(65 + mod) + colLetter;
        div = (int)((div - mod) / 26);
      }
      return colLetter;
    }