使用c#将数据更新到Excel工作表
我正在尝试使用OLEDB连接更新格式为“xlsx”的Excel工作表中的某些数据,但我无法确定连接的build立。
这是我的代码:
String sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" + "D:\abc1.xlsx" + "';Extended Properties='Excel 8.0;HDR=Yes'"; OleDbConnection con = new OleDbConnection(sConnectionString); con.Open(); OleDbCommand com = new OleDbCommand("select * from Sheet1",con); OleDbDataReader reader = null; reader = com.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader[0]); } con.Open(); Console.ReadLine(); }
当我运行代码时,我正面临以下exception:
“Microsoft.ACE.OLEDB.12.0”提供程序未在本地计算机上注册。
任何想法如何从这个exception恢复或任何其他build议,我可以在Excel中更新我的数据是可取的。
这可能是你所说的提供者,试着把它改成与你机器上的Excel版本相匹配的提供者
尝试
Provider=Microsoft.ACE.OLEDB.12.0;Data Source='D:\abc1.xlsx';Extended Properties="Excel 12.0 Xml;HDR=YES";
代替
也可能是该excel没有安装
另外检查你是否已经为你的项目引用了OLEDB库
将您的PlatformTarget
types从AnyCPU
更改为X86
。
脚步:
转到项目属性。
selectBuild
选项卡。
从PlatformTarget选项中selectX86
。
这种例外可能有多种原因。
1)您可以使用OleDbEnumerator类来找出可用的提供程序。 因此,你设置你的连接string。
2)之前,只是尝试下面的连接string。 String sConnectionString =“Provider = Microsoft.Jet.OLEDB.4.0; Data Source ='”+“D:\ abc1.xlsx”+“'; Extended Properties ='Excel 8.0; HDR = Yes'”;
3)如果你有一个64位的操作系统,没有64位版本的JET提供程序可用,没有其他select。 只要您想支持JET,就需要将构build目标设置为x86。
首先保存为Excel工作簿Excel 97-2003工作簿它将在我的项目中工作…
string filepath = Server.MapPath("~/ImportData/") + fileUpload.FileName; OleDbConnection oconn = new OleDbConnection (@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + "; Extended Properties=Excel 8.0");` oconn.Open(); OleDbDataAdapter adp = new OleDbDataAdapter("select * from Sheet1", oconn); DataSet ds = new DataSet(); adp.Fill(ds); oconn.Close();`