我想使用OLEDB使用以下代码更新Excel 2010文件。
我发现当我调试这段代码时,没有例外但excel文件列(Status)内容没有更新,有人可以帮忙吗?
P.S。 sql语句是这样的:
UPDATE [Sheet1$] SET Status ='Imported' WHERE Status IN ( SELECT TOP 5 Status FROM [Sheet1$])
。
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
StringBuilder sql = new StringBuilder();
MyConnection = new System.Data.OleDb.OleDbConnection(GetExcelConnectionStringByWrite(filePath));
MyConnection.Open();
myCommand.Connection = MyConnection;
//sql.Append("UPDATE [");
//sql.Append(sheetName);
//sql.Append("S1:S");
//sql.Append(rowNum);
//sql.Append("] SET Status ='Imported'");
//---------New Update SQL---------
sql.Append("UPDATE [");
sql.Append(sheetName);
sql.Append("] SET Status ='Imported' WHERE Status IN ( SELECT TOP ");
sql.Append(rowNum);
sql.Append(" Status FROM ");
sql.Append("[");
sql.Append(sheetName);
sql.Append("])");
//------------End-----------------
myCommand.CommandText = sql.ToString();
myCommand.ExecuteNonQuery();
MyConnection.Close();
答案 0 :(得分:0)
知道找到解决这些神秘问题的方法有多困难,我建议您发布excel文件的摘录。此外,我需要知道GetExcelConnectionStringByWrite(filePath)中会发生什么。
因为这些项目是绝对的,我只能给出两个常见的原因:
此致 扬
答案 1 :(得分:0)
我使用了完全相同的代码,但稍作修改如下,并按照需要运行。
在:
COLUMN A has fieldname called Status
A1 Status
A2 A
A3 B
A4 C
A5 D
A6 E
A7 F
代码:
using System;
using System.Data.OleDb;
namespace StackoverflowExcel
{
class Program
{
static void Main()
{
using(var myConnection = new OleDbConnection(GetExcelConnectionStringByWrite()))
using (var myCommand = new OleDbCommand())
{
myConnection.Open();
myCommand.Connection = myConnection;
myCommand.CommandText =
"UPDATE [Sheet1$] SET Status ='Imported' WHERE Status IN ( SELECT TOP 5 Status FROM [Sheet1$] )";
myCommand.ExecuteNonQuery();
myConnection.Close();
}
Console.WriteLine("Done");
Console.ReadKey();
}
private static string GetExcelConnectionStringByWrite()
{
return
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\cys\desktop\Test.xlsx;Extended Properties='Excel 12.0;HDR=YES;IMEX=0;MAXSCANROWS=10;READONLY=FALSE'";
}
}
}
后:
COLUMN A has fieldname called Status
A1 Status
A2 Imported
A3 Imported
A4 Imported
A5 Imported
A6 Imported
A7 F