Import excel sheet using jet.oledb.4.0 , setting f

2019-07-12 05:10发布

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?

标签: c# excel oledb jet
2条回答
何必那么认真
2楼-- · 2019-07-12 05:22

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.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-07-12 05:22

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'";
查看更多
登录 后发表回答