无法使用oledb将数据写入excel [英] Unable to write data to excel using oledb
问题描述
我想将某些数据写入我的excel文件,为此我使用的是OLEDB。
I want to write certain data to my excel file and for that purpose i am using OLEDB.
我有一个庞大的数据块,到$ 60000条记录。
I have a huge chunk of data which can count to maybe 50000 to 60000 records.
目前我的代码如下所示:
Currently my code is as shown below:
string connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source ={0};Extended Properties ='Excel 12.0 Xml;HDR=YES;Mode=ReadWrite';", filePath);
using (OleDbConnection cn = new OleDbConnection(connectionString))
{
String statement = "UPDATE [Sheet1$] SET [Status] = @Status, [Count] = @count WHERE [ID] = @Id";
cn.Open();
for (int index = 0; index < _listResult.Count; index++)
{
OleDbCommand cmd = new OleDbCommand(statement, cn);
cmd.Parameters.AddWithValue("@Status", _listResult[index].Status);
cmd.Parameters.AddWithValue("@count", _listResult[index].Count);
cmd.Parameters.AddWithValue("@Id", _listResult[index].Id);
cmd.ExecuteNonQuery();
}
cn.Close();
但是如果我这样做,那么数据不会更新到excel表。
But if i am doing like this then the data is not updated to the excel sheet.
相反,我移动For循环外部和内部,我打开连接并执行查询,那么它是工作fine.But这需要很多时间。
Instead i shift the For loop outside and inside that i open the connection and execute the query ,then it is working fine.But that takes a lot of time.
我在这里做错了什么?
请给我适当的方法来实现这一点。
Please give me appropriate ways to achieve this.
任何帮助将不胜感激。
注意:刚刚我发现以下代码在我运行应用程序时正常工作visual studio,但是当我采取发布版本并从那里运行它,那么它不是写数据到excel表。请帮助。
感谢
推荐答案
您需要按如下方式拆分代码:
You need to split the code as follows:
- 在循环之外 - 声明
cmd
。添加3个参数,以及它们的类型。
- Outside the loop - declare
cmd
. Add the 3 parameters to it, along with their types. DO NOT assign values at this stage. - Inside the loop - assign the appropriate values to the parameters and then execute the statement.
$ b
$ b
您的代码应该看起来像这样(我假设所有参数都是整数,所以你需要根据你的实际类型修改):
Your code should look something like this (I assumed all parameters to be integers, so you need to modify based on your actual types):
OleDbCommand cmd = new OleDbCommand(statement, cn);
cmd.Parameters.Add("@Status", OleDbType.Integer);
cmd.Parameters.Add("@count", OleDbType.Integer);
cmd.Parameters.Add("@id", OleDbType.Integer);
for (int index = 0; index < _listResult.Count; index++)
{
cmd.Parameters["@Status"].Value = _listResult[index].Status;
cmd.Parameters["@count"].Value = _listResult[index].Count;
cmd.Parameters["@Id"].Value = _listResult[index].Id;
cmd.ExecuteNonQuery();
}
这篇关于无法使用oledb将数据写入excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!