Search code examples
c#excelssisoledbscript-task

Insert Record at the top of Excel


Hi I have this C# code and it is working well:

string fileFullPath = Dts.Variables["User::ExcelFileFullPath"].Value.ToString();

            //Create Excel Connection
            ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileFullPath + ";Extended Properties=\"Excel 12.0 XML;HDR=NO\";";
            OleDbConnection cnn = new OleDbConnection(ConStr);

            //Get Sheet Name
            cnn.Open();
            DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

            foreach (DataRow drSheet in dtSheet.Rows)
            {
                if (drSheet["TABLE_NAME"].ToString().Contains("$"))
                {
                    if (drSheet["TABLE_NAME"].ToString().Contains("Survey"))
                    {
                        sheetname = drSheet["TABLE_NAME"].ToString();



                        OleDbCommand myCommand = new OleDbCommand();
                        string sql = null;


                        myCommand.Connection = cnn;
                        sql = "Insert into [" + sheetname + "] values('5','e')";
                        myCommand.CommandText = sql;
                        myCommand.ExecuteNonQuery();
                        cnn.Close();
                    }

                }
            }

But this code inserts the record at the end of the excel file and what I need to do is insert that record at the first row (A1:B1)

Any suggestion?


Solution

  • You need to specify the range beside the Sheet Name:

    sql = "Insert into [" + sheetname + "A1:B1] values('5','e')"
    

    More additional information can be found in the following question:

    If you are looking for some detailed article on performing SELECT, INSERT, UPDATE operations on EXCEL using OLEDB refer to: