我正在尝试使用OleDbConnection
插入现有的Excel电子表格。我注意到,当我插入时,即使我指定了工作表偏移量,它仍然写入错误的行。更糟糕的是,每条记录都被写入同一行!这是我的代码:
static void Main(string[] args)
{
string destination = @"C:\publish\output.xlsx";
File.Copy(@"C:\publish\template.xlsx", destination, true);
string connectionString = getConnectionString(destination);
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
using (OleDbCommand command = connection.CreateCommand())
{
command.CommandText = @"
INSERT INTO [Advertisers$A3:AC]
VALUES
(
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)";
// Spit out 29 bogus values
for (int i = 0; i != 29; ++i)
{
addParameter(command, "Value = " + i);
}
// Insert 1200 records
for (int i = 0; i != 1200; ++i)
{
command.ExecuteNonQuery();
}
}
}
}
private static string getConnectionString(string path)
{
OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder();
builder.Provider = "Microsoft.ACE.OLEDB.12.0";
builder.Add("Extended Properties", "Excel 12.0 Xml");
builder.DataSource = path;
return builder.ConnectionString;
}
private static void addParameter(OleDbCommand command, object value)
{
OleDbParameter parameter = command.CreateParameter();
parameter.ParameterName = "?";
parameter.Value = value == null ? DBNull.Value : value;
command.Parameters.Add(parameter);
}
答案 0 :(得分:0)
我基本上将相同的代码复制到不同的控制台应用程序,它按预期工作。嗯?在比较两个项目一段时间之后,我注意到在项目属性下,在Build
下,选中了Prefer 32-bit
复选框。取消选中它解决了我的问题!