i am trying to import an excel file into a datatable in using Jet.Oledb. Here is my code:
string sourceConstr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + HttpContext.Current.Server.MapPath("~/" + fileName) + "';Extended Properties='Excel 8.0;HDR=No;IMEX=1'";
OleDbConnection con = new OleDbConnection(sourceConstr);
OleDbCommand oleDbCmd = new OleDbCommand();
con.Open();
oleDbCmd.Connection = con;
DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string firstExcelSheetName=dt.Rows[0][2].ToString();
string query = "select * from [" + firstExcelSheetName + "]";
OleDbDataAdapter data = new OleDbDataAdapter(query, con);
data.TableMappings.Add("Table", "dtExcel");
data.Fill(dtExcel);
In the excel file, first row has the columnname. but my datatable is getting (f1,f2,f3,...) as column name and first row of the excel file as first row. So i can guess I have to tell that the first row contains columnName. But how can i make it happen?
Taking a quote from connectionstrings.com:
So you could try changing your connection string to set
HDR=Yes
.there is a only a little change as shown below, in the connection string i.e. sourceConstr in your case.
instead of
after change it would be