It would be strange, but maybe it is some sort of attempt of OleDb to avoid SQL Injection? (What if row["Name"]
contains a single quote?) Even if it does not explain, like @Treb said, why there is a leading quote only, without a trailing one.
What happens if you try to use the query with parameters, ie.:
using (OleDbCommand addLine = new OleDbCommand("INSERT INTO Data1 values (@name, @age)"))
{
addLine.Parameters.AddWithValue("@name", row["Name"]);
addLine.Parameters.AddWithValue("@age", row["Age"]);
int affectedRows = addLine.ExecuteNonQuery();
Debug.Assert(1 == affectedRows);
}
After a few attempts, I still can't reproduce the observed behavior. I suggest to do several things:
Post in your question the whole source code which produces the single quote problem,
Try the following source (Console application) and see what happens. In my case, values are inserted well, without any leading single quotes. The only problem are the ages, inserted as text instead of numbers (which can probably be solved by explicitly specifying the type of the row):
Source code:
namespace Demos.StackOverflow.ExcelUpdate
{
using System;
using System.Collections.ObjectModel;
using System.Data.OleDb;
class Program
{
static void Main(string[] args)
{
// -> Change the following name of the file to use.
string fullPath = @"C:\Users\Arsene\Desktop\Book1.xlsx";
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0'", fullPath);
Collection<Tuple<string, int>> dataToPut = new Collection<Tuple<string, int>>();
dataToPut.Add(new Tuple<string, int>("Some name", 34));
dataToPut.Add(new Tuple<string, int>("Other name here", 41));
dataToPut.Add(new Tuple<string, int>("Last one", 36));
using (OleDbConnection oleConnection = new OleDbConnection(connectionString))
{
oleConnection.Open();
using (OleDbCommand createTable = new OleDbCommand("create table Data1 (Name char(10), Age char(10))", oleConnection))
{
createTable.ExecuteNonQuery();
}
foreach (var t in dataToPut)
{
using (OleDbCommand addItem = new OleDbCommand("insert into Data1 values (@name, @age)", oleConnection))
{
addItem.Parameters.AddWithValue("@name", t.Item1);
addItem.Parameters.AddWithValue("@age", t.Item2);
addItem.ExecuteNonQuery();
}
}
}
}
}
}