简体   繁体   English

从 C# 中的索引获取.xlsx 列名

[英]Get .xlsx column name from index in C#

I would like to create a function that will convert a number to.csv file column.我想创建一个 function 将数字转换为 .csv 文件列。

For example:例如:

  • Number 5 -> Column E数字 5 -> E
  • Number 29 -> Column AB编号 29 -> AB

and so on..等等..

I've made this function so far:到目前为止,我已经制作了这个 function:

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).如果数字超过 26(字母的长度),我就会陷入困境。

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.这是您提出的问题,但我必须注意,我同意@Martin Holy 的回答:如果可能的话,经过测试的用户权限工具已经过修补。

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: 将 Excel 列号转换为列名或字母:

Also, unless I am missing something… would not 29 -> AC?另外,除非我遗漏了什么……不会 29 -> AC?

… 26=Z, 27=AA, 28=AB and 29=AC … … 26=Z、27=AA、28=AB 和 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM