首页 > 其他 > 详细

23. Excel数转换

时间:2014-02-26 01:15:28      阅读:292      评论:0      收藏:0      [点我收藏+]

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。

 

bubuko.com,布布扣
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

23. Excel数转换

原文:http://www.cnblogs.com/Ligeance/p/3566910.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!