23. Excel数转换

Excel中的行列数用A~Z 26个字母表示,A, B, C, D, …, Z, AA, AB, …, AZ, BA, BB, … 分别表示10进制数1, 2, 3, 4, …, 26, 27, 28, …, 52, 53, 54…。

请实现2个函数decToExcelexcelToDec,将10进制数转换为Excel数,以及将Excel数转换为10进制数。

有个小BUG,当26的时候显示为@A……不知道为啥会这样。已修复@A的BUG。

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication21
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(DecToExcel(26));
            Console.WriteLine(ExcelToDec("AB"));
        }

        static string DecToExcel(int n)
        {
            if (n <= 0)
            {
                throw new Exception("input must greater than zero");
            }
            StringBuilder sb = new StringBuilder();
            int a = 0;
            while (n > 0)
            {
                a = (n - 1) % 26;
                n = (n - 1) / 26;
                sb.Insert(0, ((char)(a + 'A')));
            }

            return sb.ToString();
        }

        static int ExcelToDec(string input)
        {
            int result = 0;
            for (int i = 0; i < input.Length; i++)
            {
                result = result * 26 + input[i] - 'A' + 1;
            }
            return result;
        }
    }
}
View Code

 

posted @ 2014-02-25 15:49  Ligeance  阅读(191)  评论(0编辑  收藏  举报