简体   繁体   中英

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).

Here is what you asked but I must note that I agree with @Martin Holy's answer: if possible user right tools that are tested tinkered.

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

        const int alpha_count = 26;

        char alpha = (char)64;

        int div = index / 26;

        if (div > 0)
        {
            col.Append(((char)(alpha + div)).ToString());
        }

        col.Append(((char)(alpha + (index - (div * 26))  )).ToString());

        return col.ToString();
    }

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;
}

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