Click here to Skip to main content
14,875,113 members
Please Sign up or sign in to vote.
4.00/5 (5 votes)
I would like to extract / retrieve only the COLUMN NAMES OF AN EXCEL sheet using c sharp. For example an excel sheet has data in following structure:-
TITLE   | FIRST NAME | LAST NAME
-----------------------------------
Ms.     | Jeannette  | Higgi
Mr.     | Ian        | Botham
Mr.     | Lawrence   | Bocha

Sheet1 (sheet name)

The output should be:-
TITLE
FIRST NAME
LAST NAME


Your valuable suggestion is highly appreciated.

Thanks in advance.

Mohandas.
Posted
Updated 22-May-11 21:32pm
v3

Firstly Take ur excel data in dataset or datatable.
Then u can use ColumnName property to extract Columns name like

MIDL
dt.Columns[0].ColumnName


Be sure Column name Should be first row of excel.
   
v2
Comments
Mohandas_Kulasekaran 23-May-11 3:30am
   
In real time excel sheet, there are over 60000 rows with 40 columns. I want only the column names without having to waste my system resource taking the excel data to a dataset or datatable.
Ashishmau 23-May-11 4:07am
   
Its not possible without taking it in dataset or Other way u can use dll like LinqToExcel.dll to retrieve columns name.see the links i mentioned below and download dlls for your use.
Dalek Dave 23-May-11 4:48am
   
Good answer.
Try below code snippet:
You need to add "Microsoft Excel 12.0 Object Library" to your project

using Microsoft.Office.Interop.Excel;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Microsoft.Office.Interop.Excel.Application app = new ApplicationClass();
Workbook workBook = app.Workbooks.Open(@"your_file_path",
0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Worksheet workSheet = (Worksheet)workBook.Worksheets.get_Item(1);
Range range = workSheet.UsedRange;
for (int i = 1; i <= range.Columns.Count; i++)
{
Console.WriteLine(((Range)range.Cells[2, i]).Value2);
}
Console.ReadLine();
}
}
}

Reference: http://csharp.net-informations.com/excel/csharp-read-excel.htm[^]
   
Comments
Dalek Dave 23-May-11 4:48am
   
Excellent suggestion, so long as you know the row the column names are in, but it is a method I would employ.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900