0

I am taking Excel data into DataTable but it is taking Excel Column name as first row of data in DataTable. So help me to set Excel's first row as columns in DataTable. PS: I am using Microsoft.Offfice.Interop.Excel and System.Data.DataTable namespace This is my code:

connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
new System.Data.OleDb.OleDbDataAdapter(cmdExcel).Fill(dt);
connExcel.Close(); 

I am getting all the data of specified excel sheet into DataTable dt but it is taking Excel column names as first row of data in Datatable

S_PATIL
  • 3
  • 1
  • 5

3 Answers3

0
DataTable tab = new DataTable();
for (int i = 0; i < tab.Columns.Count; i++)
{
    tab.Columns[i].Caption = "example"
}
Alexey Subach
  • 11,903
  • 7
  • 34
  • 60
skazied
  • 46
  • 3
  • 1
    Thanks, but what if user altered Excel Sheet before uploading and set "example" as 3rd Column? Then with above code i will have wrong data in wrong column – S_PATIL Nov 16 '17 at 10:41
0

Hey you can do the following, it will disable taking the header from the excel workbook:

    conn = New System.Data.OleDb.OleDbConnection(
          "provider=Microsoft.ACE.OLEDB.12.0; " &
          "data source=" & path & "; " &
          "Extended Properties=""Excel 12.0;HDR=No;IMEX=1""")

Alter the HDR to No in the connection string

JKOU
  • 255
  • 2
  • 14
0

To change a column name, use ColumnName.

DataTable table = new DataTable();

table.Columns.Add("A", typeof(int));
table.Columns.Add("B", typeof(string));

table.Columns[0].ColumnName = "Column A";
table.Columns[1].ColumnName = "Column B";

table.Rows.Add(99, "test row");
VDWWD
  • 35,079
  • 22
  • 62
  • 79