簡體   English   中英

從 C# 中的索引獲取.xlsx 列名

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

我想創建一個 function 將數字轉換為 .csv 文件列。

例如:

  • 數字 5 -> E
  • 編號 29 -> AB

等等..

到目前為止,我已經制作了這個 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);

    }
}

如果數字超過 26(字母的長度),我就會陷入困境。

這是您提出的問題,但我必須注意,我同意@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();
    }

我以前用過這個,應該像你描述的那樣工作……這來自……

將 Excel 列號轉換為列名或字母:

另外,除非我遺漏了什么……不會 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