Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Microsoft Interop: Excel Column Names

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

like image 470
Priyank Thakkar Avatar asked Mar 15 '12 13:03

Priyank Thakkar


1 Answers

     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.

like image 164
Jetti Avatar answered Oct 21 '22 20:10

Jetti