我在程序中使用OLEDB更新Excel工作表。 Execute返回1作为行更新计数,但不做任何更改。 我的代码如下:
public static void updateExcel(string sql, string path)
{
try
{
OleDbConnection con;
OleDbCommand comm = new OleDbCommand();
con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
path +
";Extended Properties=Excel 12.0;");
con.Open();
comm.Connection = con;
comm.CommandText = sql;
int y = comm.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
}
}
呼叫是:
string sql = "update [Sh1$] set j = j + ' AAAA ' where a = '" + excelData.Rows[i]["a"].ToString() + "'";
EXCEL.updateExcel(sql, excelFile);
有人知道出什么问题吗?
谢谢!
答案 0 :(得分:1)
尝试使用以下方式进行重写:
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = @"update [Sh1$] set j = j + ' AAAA ' where a = '" + excelData.Rows[i]["a"].ToString() + "'";
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
//exception here
}
finally
{
conn.Close();
conn.Dispose();
}
}
答案 1 :(得分:0)
检查excel中的单元格是否为空。如果是这样,则此set j = j + ' AAAA '
将不起作用,因为j
是NULL
。
在这种情况下,这会更好:
set j = ' AAAA '
或
set j = IIF(j IS NULL, ' AAAA ', j + ' AAAA ')