尝试连接到C#中的Excel电子表格

我试图从一个电子表格拉一堆数据,但是我无法在我的C#代码中成功连接。 乙

下面是连接string和我用来build立连接的代码。 该程序的目标是从电子表格中提取数据并将其存入SQL数据库。 我不能通过connection.open()命令,但不会收到此错误信息:

“外部表格不是预期的格式”

string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\nearod\Desktop\TestLoad.xlsx;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; string queryString = "SELECT * FROM [SQL AgentUnique ID Test Load$]"; try { OleDbDataReader reader; using (OleDbConnection connection = new OleDbConnection(connectionString)) { OleDbCommand command = new OleDbCommand(queryString, connection); connection.Open(); reader = command.ExecuteReader(); while (reader.Read()) { counter++; //Access db values string compCode = ""; string agId = ""; string fName = ""; string lName = ""; string nameSuffix = ""; compCode = reader.GetValue(0).ToString(); agId = reader.GetString(1); fName = reader.GetString(2); lName = reader.GetString(3); nameSuffix = reader.GetString(4); sqlComm.Parameters.Add(companyCode); sqlComm.Parameters.Add(agentID); sqlComm.Parameters.Add(firstName); sqlComm.Parameters.Add(lastName); sqlComm.Parameters.Add(suffix); //Initialize connection objects cm = Dts.Connections["QUAHILSQ03"]; sqlConn = (SqlConnection)cm.AcquireConnection(Dts.Transaction); sqlComm = new SqlCommand("AgentResourcesU01.dbo.sp_AgentIdAprCheck", sqlConn); sqlComm.CommandType = CommandType.StoredProcedure; //Execute stored procedure sqlComm.ExecuteNonQuery(); } reader.Close(); connection.Close(); OleDbConnection.ReleaseObjectPool(); } 

对于* .xlsx,您需要Ace驱动程序:Microsoft.ACE.OLEDB.12.0

 string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\nearod\Desktop\TestLoad.xlsx; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; 

很久以前写了这个。 它在WebForms中,但.cs文件显示您需要: 将Excel电子表格转换为数据集,数据表和multidimensional array

 string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+FileToConvert+";Extended Properties=Excel 8.0;"; try { OleDbConnection connection = new OleDbConnection(connectionString); connection.Open(); //this next line assumes that the file is in default Excel format with Sheet1 as the first sheet name, adjust accordingly OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connection); DataSet ds = new DataSet(); DataTable dt = new DataTable(); adapter.Fill(ds);//now you have your dataset ds now filled with the data and ready for manipulation // do stuff }