2024年4月24日 星期三

[研究][C#]整數轉 Excel 橫列標題 26進位轉換

[研究][C#]整數轉 Excel 橫列標題 26進位轉換

2024-04-24

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

********************************************************************************

Excel的橫列標題是 A,B,C, ... Z, AA, AB, .... 依此類推,

10進位 => 26進位 ( 0->A, 1->B, ....)

using System;

class Program
{
    static string ConvertToBase26(int number)
    {
        const string base26Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        string result = string.Empty;

        do
        {
            result = base26Chars[number % 26] + result;
            number /= 26;
        } while (number-- > 0);

        return result;
    }

    static void Main()
    {
        int number = 12345;
        string base26 = ConvertToBase26(number);
        Console.WriteLine($"Number {number} in base 26 is {base26}");
    }
}



26進位 => 10進位


using System;

class Program
{
    static int ConvertFromBase26(string base26)
    {
        const string base26Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        int result = 0;

        for (int i = 0; i < base26.Length; i++)
        {
            result = result * 26 + base26Chars.IndexOf(base26[i]);
        }

        return result;
    }

    static void Main()
    {
        string base26 = "BCDE";
        int number = ConvertFromBase26(base26);
        Console.WriteLine($"Base 26 number {base26} is {number} in base 10");
    }
}




(完)

相關

沒有留言:

張貼留言