Microsoft Interop: Excel Column Names

Priyank Thakkar picture Priyank Thakkar · Mar 15, 2012 · Viewed 35.9k times · Source

I am using Microsoft Interop to read the data.

In excel-sheet the column-names are like A,B,C,D,....,AA,AB,.... and so on. Is there any way to read this column-names?

If you need any other info please let me know.

Regards, Priyank

Answer

Jetti picture Jetti · Mar 15, 2012
     Excel.Application xlApp = new Excel.Application();
     Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("workbookname");
     Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1]; // assume it is the first sheet
     int columnCount = xlWorksheet.UsedRange.Columns.Count;
     List<string> columnNames = new List<string>();
     for (int c = 1; c < columnCount; c++)
     {
         if (xlWorksheet.Cells[1, c].Value2 != null)
         {
             string columnName = xlWorksheet.Columns[c].Address;
             Regex reg = new Regex(@"(\$)(\w*):");
             if (reg.IsMatch(columnName))
             {
                 Match match = reg.Match(columnName);             
                 columnNames.Add(match.Groups[2].Value);
             }                      
        }
     }

This will put each column name in a List<string> which you can then bind to a drop down box.