0

I am using MS Excel as my datasource. I have one table in one of the workbook. When I retrieve the data from table I need column name as per MS Excel (e.g. A, B, C,... AA, AB... and so on.)

Is there any way to achieve it?

Please guide me.

1
  • The column names are always fixed in Excel. One of teh possible ways can be to get the column number and pass it to a function which will return the actual coulmn name. Commented Dec 7, 2011 at 11:12

1 Answer 1

2

Very easy I made a method once for this, all you need is a column number and it will convert it to a string as "aa" or "bb"

private static string chars ="ABCDEFGHIJKLMNOPQRSTUVWXYZ";

private static string ConvertNumber(int number)
{
  string result;
  number -= 1;
  int rest = number % 26;
  int q = number / 26;
  if(q == 0)
  {
    result = chars[rest].ToString();
  }else{
    result = ConvertNumber(q) + chars[rest];
  }
  return result;
}

This only works when your first column isn't index = 0, but index = 1. That is because the 'A' is not the same as a '0' like in the normal numeral systems. If it where then AB would be 0 * 26^1 + 1 * 26^0

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for wonderful input and such a timely reply :) :) cherio
@PriyankThakkar: np, i had this code sitting in on off my projects here. Copy paste and some comments and its done :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.