Click here to Skip to main content
15,902,114 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear Sir/Madam,

I would like to use the sql statements in Excel file. I am able to fetch records from excel using OleDb object. But I am unable to use Insert/Update queries. For an example I have given the code below. kindly Help me out.
C#
public static int InsertExcelData()
        {
            int rowAffectecd=0;
            DataTable dtRecords = new DataTable();
            OleDbCommand excelCommand = new OleDbCommand();
            OleDbDataAdapter excelDataAdapter = new OleDbDataAdapter();
            try
            {
                //DataSet ds = new DataSet();
                string excelConnStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=@"D://myExcel.xls"; Extended Properties =Excel 8.0;";
                OleDbConnection excelConn = new OleDbConnection(excelConnStr);
                excelConn.Open();
                string[] sSheetName = Common.GetExcelSheetNames(Common.excelFilePath);
                excelCommand = new OleDbCommand(" INSERT INTO ["Sheet1$"](Name) VALUES('John');", excelConn);

                excelCommand.CommandType = CommandType.Text;
                excelCommand.CommandTimeout = 0;
                rowAffectecd = excelCommand.ExecuteNonQuery();
            }
            catch (Exception err)
            {
                  throw err;
            }
            return rowAffectecd;
        }

Note:
I have the excel file with Name column.
Posted
Updated 1-Dec-11 22:11pm
v2
Comments
Ankit Rajput 2-Dec-11 4:23am    
What is the problem with code?
thatraja 2-Dec-11 5:32am    
what's the error message?

1 solution

When you say "Name" columns do you mean a Range or a column with "Name" as the first row element?? If the latter is the case, your query might fail. You should specify the cell range next to the sheet name. Also the double quote around Sheet1$ should be padded.
SQL
INSERT INTO [""Sheet1$""](Name) VALUES('John');
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900