Thursday, July 5, 2012

Insert Data from Excel to Access Using OLEDBDataAdapter

The view of this article is to show use of dataAdapter to update Database.

string file = Application.StartupPath + @"\excel.xlsx";
            DataSet ds = ImportExcelXLS(file, true);

            //SqlConnection conn = new SqlConnection("Data Source=server;Initial Catalog=TestDB;User Id=sa;Password=#######;");
            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + @"\test.accdb" + ";Persist Security Info=False;");

            try
            {
                conn.Open();

                DataSet dataSet = new DataSet();

                //SqlDataAdapter adapt = new SqlDataAdapter("select * from test where 0 = 1", conn);
                OleDbDataAdapter adapt = new OleDbDataAdapter("select * from test where 0 = 1", conn);

                //SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapt);
                OleDbCommandBuilder sqlBld = new OleDbCommandBuilder(adapt);

                adapt.MissingSchemaAction = MissingSchemaAction.AddWithKey;
                adapt.Fill(dataSet, "test");

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    DataRow Newrow = dataSet.Tables["test"].NewRow();
                    Newrow.ItemArray = row.ItemArray;
                    dataSet.Tables["test"].Rows.Add(Newrow);
                }

                //sqlBld = new SqlCommandBuilder(adapt);
                sqlBld = new OleDbCommandBuilder(adapt);

                adapt.InsertCommand = sqlBld.GetInsertCommand();
                adapt.Update(dataSet, "test");

                endTime = System.DateTime.Now;

                TimeSpan result = endTime - startTime;
                string result2 = result.ToString();

                MessageBox.Show("Done\nIt took "  + result2 +" to write data");
            }
            catch(Exception exec)
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show(exec.Message);  
            }
            finally
            {
                this.Cursor = Cursors.Default;
                if (conn.State == ConnectionState.Open)
                    conn.Close();
            }

for ImportExcelXLS(file, true);
Please read my previous Post