10

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

Priyank Thakkar
  • 4,752
  • 19
  • 57
  • 93

2 Answers2

15
     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.

Jetti
  • 2,418
  • 1
  • 17
  • 25
  • 1
    Where do you find the doc concerning the whole interop.excel namespace ? By looking at the MSDN, I cant seem to find anything interesting. – squelos Mar 15 '12 at 14:45
  • @squelos you can find some information [from MSDN here](http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel(v=office.11).aspx). Other info I got from a book. I also have a blog post which you can read [here](http://dontbreakthebuild.com/2011/01/30/excel-and-c-interop-with-net-4-how-to-read-data-from-excel/) that deals with reading Excel data with C# and .NET 4.0 – Jetti Mar 15 '12 at 14:53
  • 1
    good starting point for me! I had wanted to copy the column names from Excel over to a CSV file and adjusted your code to columnNames.Add(xlWorksheet.Cells[1, c].Value); Thanks! – Rob Koch May 10 '13 at 21:37
  • The last column was missing: for (int c = 1; c <= columnCount; c++) – jcmeyrignac Nov 18 '22 at 14:41
0

You can also Read Column By index

let your Excel work Sheet object is "excelWorksheet" then you can access it as

for setting a value you can use

excelWorksheet.Cells[rowindex, columnindex].Value = "test";

for getting a value you can use

string result = excelWorksheet.Cells[rowindex, columnindex].Value ;

Remember that fields are dynamically generated so it may show error in writing your code but ignore that

for example you want to set text in excel sheet row 1 & column 2 then

excelWorksheet.Cells[1, 2].Value = "test";

I have used it & it works perfectly

Shivam Srivastava
  • 4,496
  • 2
  • 23
  • 24