Ham*_*eez 2 .net c# oledb excel
我正在尽力在 excel 文件中插入一个新的数据行。请看一看。我正在使用 C#.net 框架 (3.5) 面临这个问题
代码:
try{
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\rising rent\\csharp-Excel.xls;Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;MAXSCANROWS=15;READONLY=FALSE;ImportMixedTypes=Text'";
OleDbConnection conn = new OleDbConnection(ConnectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO [Inventory$] (C_DATE) VALUES('555')",conn);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Run Code Online (Sandbox Code Playgroud)
错误是这样的,请查看并分享您的观点
“System.Data.OleDb.OleDbException:操作必须使用可更新的查询。在 System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) 在 System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, System Object.executeResult) Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at RisingRentACar.Inventory.button1_Click(Object sender, EventArgs e) 在 C:\Users\Hamza Hafeez\Documents\Visual Studio 2015\Projects\RisingRentACar\RisingRentACar\Inventory.cs:line 82"
所以你的解决方案很接近,我知道这已经四个多月了,但可以帮助其他人。我遇到了同样的问题,终于让它工作了。
您不需要连接字符串中的所有内容。这对我有用。
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ FileNameAndPath + ";Extended Properties=\"Excel 12.0 Xml; HDR=YES\";";
Run Code Online (Sandbox Code Playgroud)
"HDR=YES"表示第一行有标题单元格。您可以使用列名插入。
其次,查询必须在列名周围有 []。喜欢:
command.CommandText = "Insert into [Sheet1$] ([ColumnName]) values('Value')";
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助像我这样看过这篇文章的其他人寻找这个问题的答案。
这是我的整个解决方案:
private void InsertData(List<string> columnNames, List<string> theValues)
{
OleDbConnection connection = null;
OleDbCommand command = null;
string connectionString = "";
string columns = "";
string values = "";
try
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtDestination.Text + ";Extended Properties=\"Excel 12.0 Xml; HDR=YES\";";
using (connection = new OleDbConnection(connectionString))
{
connection.Open();
for (int index = 0; index < columnNames.Count; index++)
{
columns += (index == 0) ? "[" + Regex.Replace(columnNames[index], @"\t|\n|\r", "\"") + "]" : ", [" + Regex.Replace(columnNames[index], @"\t|\n|\r", "\"") + "]";
values += (index == 0) ? "'" + Regex.Replace(theValues[index], @"\t|\n|\r", "\"") + "'" : ", '" + Regex.Replace(theValues[index], @"\t|\n|\r", "") + "'";
}
using (command = connection.CreateCommand())
{
command.CommandText = string.Format("Insert into [Sheet1$] ({0}) values({1})", columns, values);
command.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
ProcessError(ex);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8973 次 |
| 最近记录: |