Tuesday, December 16, 2008

SpreadsheetML - Convert column integer index to column alpha value(i.e. A, AA, BH)

Here's a quick snippet I found in a forum post at http://stackoverflow.com/questions/181596/how-to-convert-a-column-number-eg-127-into-an-excel-column-eg-aa. Many times in Excel I want to use a column index value instead of the letter representation(i.e A, AA, BH). I don't have control of the Excel so I can't change the representation. This method returns the letter representation from an integer column value.


  1. protected string GetExcelColumnName(int columnNumber)  
  2.         {  
  3.             int dividend = columnNumber;  
  4.             string columnName = String.Empty;  
  5.             int modulo;  
  6.   
  7.             while (dividend > 0)  
  8.             {  
  9.                 modulo = (dividend - 1) % 26;  
  10.                 columnName = Convert.ToChar(65 + modulo).ToString() + columnName;  
  11.                 dividend = (int)((dividend - modulo) / 26);  
  12.             }  
  13.   
  14.             return columnName;  
  15.         }  

2 comments:

Anonymous said...

Yeah, finally one that works.
Have been searching all day.

Thanks

Daniel said...

Thank you for this code snippet.