Updating the Data
Use the adapter's Update method to update the data. This overloaded method can take a DataTable as a parameter and will commit all the changes made to the data source. The name of the data table can be passed as an argument and can also be used to update the entire dataset in a more traditional manner. When using a data table as an argument to the Update method, the adapter evaluates the changes that have been made to the data table and executes the appropriate command for each row (INSERT, UPDATE, or DELETE).
The example below updates the LastName of one of the Sheet entries.
C#
using (ExcelConnection connection = new ExcelConnection(connectionString)) { ExcelDataAdapter dataAdapter = new ExcelDataAdapter( "SELECT RowId, LastName FROM Sheet", connection); dataAdapter.UpdateCommand = new ExcelCommand( "UPDATE Sheet SET LastName = @LastName " + "WHERE RowId = @RowId", connection); dataAdapter.UpdateCommand.Parameters.Add(new ExcelParameter("@LastName", DbType.String, "LastName")); dataAdapter.UpdateCommand.Parameters.Add(new ExcelParameter("@RowId", DbType.String, "RowId")); dataAdapter.UpdateCommand.Parameters[1].SourceVersion = DataRowVersion.Original; DataTable table = new DataTable(); dataAdapter.Fill(table); DataRow firstrow = table.Rows[0]; firstrow["LastName"] = "Smith"; dataAdapter.Update(table); Console.WriteLine("Rows after update."); foreach (DataRow row in table.Rows) { Console.WriteLine("{0}: {1}", row["RowId"], row["LastName"]); } }
VB.NET
Using connection As New ExcelConnection(connectionString) Dim dataAdapter As New ExcelDataAdapter( "SELECT RowId, LastName FROM Sheet", connection) dataAdapter.UpdateCommand = New ExcelCommand( "UPDATE Sheet SET LastName = @LastName " + "WHERE RowId = @RowId", connection) dataAdapter.UpdateCommand.Parameters.Add(new ExcelParameter("@LastName", DbType.String, "LastName")) dataAdapter.UpdateCommand.Parameters.Add(new ExcelParameter("@RowId", DbType.String, "RowId")) dataAdapter.UpdateCommand.Parameters(1).SourceVersion = DataRowVersion.Original Dim table As New DataTable() dataAdapter.Fill(table) Dim firstrow As DataRow = table.Rows(0) firstrow("LastName") = "Smith" dataAdapter.Update(table) Console.WriteLine("Rows after update.") For Each row As DataRow In table.Rows Console.WriteLine("{0}: {1}", row("RowId"), row("LastName")) Next End Using