Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a number to a letter in C# for use in Microsoft Excel [duplicate]

Possible Duplicate:
How to convert a column number (eg. 127) into an excel column (eg. AA)

Ok so I am writing a method which accepts a 2d array as a parameter. I want to put this 2d array onto an Excel worksheet but I need to work out the final cell location. I can get the height easily enough like so:

var height = data.GetLength(1); //`data` is the name of my 2d array

This gives me my Y axis but it's not so easy to get my X axis. Obviously I can get the number like so:

var width = data.GetLength(0);

This gives me a number, which I want to convert to a letter. So, for example, 0 is A, 1 is B and so on until we get to 26 which goes back to A again. I am sure that there is a simple way to do this but I have a total mental block.

What would you do?

Thanks

like image 236
JMK Avatar asked Apr 29 '12 15:04

JMK


People also ask

How do you turn a number into a character?

char a = Character. forDigit(num1, 10); We have used the forDigit() method converts the specified int value into char value. Here, 10 and 16 are radix values for decimal and hexadecimal numbers respectively.

Can we convert int to char in C?

We can convert an integer to the character by adding a '0' (zero) character. The char data type is represented as ascii values in c programming. Ascii values are integer values if we add the '0' then we get the ASCII of that integer digit that can be assigned to a char variable.

How do you convert a number to ASCII?

You can use one of these methods to convert number to an ASCII / Unicode / UTF-16 character: You can use these methods convert the value of the specified 32-bit signed integer to its Unicode character: char c = (char)65; char c = Convert. ToChar(65);


1 Answers

Here's a version that also handles two-letter columns (after column Z):

static string GetColumnName(int index)
{
    const string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    var value = "";

    if (index >= letters.Length)
        value += letters[index / letters.Length - 1];

    value += letters[index % letters.Length];

    return value;
}
like image 88
Cristian Lupascu Avatar answered Oct 05 '22 23:10

Cristian Lupascu