Question

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?

Was it helpful?

Solution

Taking a quote from connectionstrings.com:

"HDR=Yes;" indicates that the first row contains columnnames, not data. "HDR=No;" indicates the opposite.

So you could try changing your connection string to set HDR=Yes.

OTHER TIPS

there is a only a little change as shown below, in the connection string i.e. sourceConstr in your case.

HDR=Yes 

instead of

HDR=No

after change it would be

string sourceConstr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + HttpContext.Current.Server.MapPath("~/" + fileName) + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top