Convert a given column number to excel column header

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

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 10000; i++)
            {
                int columnNumber = i;
                char[] alphabets = {'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y'};
                string columnHeader = "";
                if (columnNumber > 0)
                {
                    while (columnNumber > 0)
                    {
                        columnHeader = columnHeader + alphabets[columnNumber % alphabets.Length].ToString();
                        if (columnNumber % alphabets.Length == 0)
                        {
                            columnNumber--;
                        }
                        columnNumber = columnNumber / alphabets.Length;
                    }
                }
                Console.WriteLine(i + " --> " + Reverse(columnHeader));
                Console.ReadLine();
            }
        }

        public static string Reverse(string text)
        {
            if (text == null) return null;
            char[] array = text.ToCharArray();
            Array.Reverse(array);
            return new string(array);
        }
    }
}
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s