1

I was trying to insert data into the second sheet in an excel file, but it gives syntax error. I tried inserting with the same syntax in sheet1 and it was working fine. The sheet name is correct, column names are correct. My code is

try
{
    System.Data.OleDb.OleDbConnection MyConnection;
    System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
    string sql = null;
    MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='d:\\contacts_moorthy.xls';Extended Properties=Excel 8.0;");
    MyConnection.Open();
    myCommand.Connection = MyConnection;
    sql = "insert into [Sheet2$] (To,Message,SentOn) values ('" + phonetxtbox.Text + "','" + messagetxtbox.Text + "','"+DateTime.Now+"')";
    myCommand.CommandText = sql;
    myCommand.ExecuteNonQuery();
    MyConnection.Close();
}
catch (Exception ex)
{
     MessageBox.Show("Error :",ex);
}
5
  • Can you share your connection setup as well? Commented Oct 18, 2012 at 6:05
  • Why are you not using the Excel automation interface in stead of the SQL approach? See for example support.microsoft.com/kb/302084 Commented Oct 18, 2012 at 6:10
  • @kdmurray i have added the connection also..pls help Commented Oct 18, 2012 at 6:47
  • @ReinierTorenbeek i am a fresher. i was working with this codes. Sure i will try the one u mentioned Commented Oct 18, 2012 at 6:48
  • I got the answer. If i don't specify the column names (To,Message,SentOn) it's working. i don'o why it is not working with the names,but the names are exact. Commented Oct 18, 2012 at 9:26

2 Answers 2

2

I think it is is in your connection string for the Jet Provider.

http://www.connectionstrings.com/excel

The connection string has n attribute called HDR. If you add "HDR=Yes;" to your connection string should indicates that the first row contains columnnames, which should solve your issue.

Sign up to request clarification or add additional context in comments.

Comments

-1

In my personal experience I noticed that it does not allow saving in Excel when the column names are not indicated in brackets "[]", that is to say it would be ... ([To], [Message], [SentOn] ).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.