将数据从Excel导入到C#中的数据库

我需要使用编码指令将数据从Excel导入数据库。
但它给了我一个错误。 “位置0没有排。” 在第11行。
在此期间,我应该replace我的表名而不是第8行中的“TABLE”?

以下是我的代码:

public static DataTable ReadExcelWithoutOffice(string filePath) { var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=YES;TypeGuessRows=0;FirstRowHasNames=true;ImportMixedTypes=Text\""; ; using (var conn = new OleDbConnection(connectionString)) { conn.Open(); var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); using (var cmd = conn.CreateCommand()) { cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] "; var adapter = new OleDbDataAdapter(cmd); var ds = new DataSet(); adapter.Fill(ds); return ds.Tables[0]; } } } 

谢谢大家的回答。 我发现了一些其他方式来解决我的问题这里是我的代码:

  System.Data.OleDb.OleDbConnection MyConnection; System.Data.DataSet DtSet; System.Data.OleDb.OleDbDataAdapter MyCommand; MyConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='D:\\C# Projects\\ex.xlsx';Extended Properties=Excel 8.0;"); MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection); MyCommand.TableMappings.Add("tbl_info", "tbl_info"); DtSet = new System.Data.DataSet(); MyCommand.Fill(DtSet); dgv.DataSource = DtSet.Tables[0]; MyConnection.Close(); 

来源: 读取和导入Excel文件到数据集

看看这个链接。

从C#读取Excel文件

所以,就是这样。

使用Microsoft Jet:首先创build一个连接

 string Con2 = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + @";Extended Properties='Excel 12.0;IMEX=1'"; System.Data.OleDb.OleDbConnection ExcelConnection = new System.Data.OleDb.OleDbConnection(Con2); 

然后做一些像…

 DataSet ds = new DataSet(); // Create OleDbCommand object and select data from worksheet TABNAME OleDbCommand cmd_hulpkostenplaatsen = new OleDbCommand("SELECT * FROM [TABNAME$]", ExcelConnection); OleDbDataAdapter oleda_hulpkostenplaatsen = new OleDbDataAdapter(); oleda_hulpkostenplaatsen.SelectCommand = cmd_hulpkostenplaatsen; oleda_hulpkostenplaatsen.Fill(ds, "HULPKOSTENPLAATSEN"); foreach (DataRow row in ds.Tables["HULPKOSTENPLAATSEN"].Rows) { } 

这个链接也是有帮助的。

http://www.c-sharpcorner.com/blogs/import-excel-data-to-database-using-c-sharp1