[英]How to insert a new Row in Excel sheet using Microsoft.Ace.Oledb in VS 2012 using c#
[英]How to insert a new row in excel using oledb c#.net
我正在尽力在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());
}
错误是这个,请看一下并分享您的观点
“ System.Data.OleDb.OleDbException:操作必须在System.Data.OleDb.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams,对象和执行结果)的System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)处使用操作。 System.Data.OleDb.OleDbCommand.ExecuteNonQuery()处System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior,String method)处的Data.OleDb.OleDbCommand.ExecuteCommandText(Object&executeResult)在RisingRentACar.Inventory.button1_Click(Object sender, C:\\ Users \\ Hamza Hafeez \\ Documents \\ Visual Studio 2015 \\ Projects \\ RisingRentACar \\ RisingRentACar \\ Inventory.cs:第82行中的EventArgs e)
因此,您的解决方案已经接近完成,我知道这已经超过四个月了,但是可以帮助其他人。 我遇到了同样的问题,终于让它起作用了。
您不需要连接字符串中的所有内容。 这对我有用。
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ FileNameAndPath + ";Extended Properties=\"Excel 12.0 Xml; HDR=YES\";";
"HDR=YES"
表示第一行具有标题单元。 您可以使用列名插入。
其次,查询必须在列名前后使用[]。 喜欢:
command.CommandText = "Insert into [Sheet1$] ([ColumnName]) values('Value')";
希望这对像我这样看过这个问题的人的其他人有所帮助。
这是我的整个解决方案:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.