Click to See Complete Forum and Search --> : Writing to an Excel File [C#]


Shaitan00
September 6th, 2005, 08:25 AM
Given the following code that connects to an Excel File (as a DB) and reads (works great) and writes (doesn't work - this is the problem).

The Excel file itself (C:\myData.XLS Sheet1) looks like this:
row(1): Client1 Assignment1 RUNNING
row(2): Client1 Assignment2 PAUSED
row(3): Client2 Assignment1 FINISHED
(spaces delimited between columns)


using System.Data;
using System.Data.OleDb;

DataSet DS;
OleDbDataAdapter MyCommand;
OleDbConnection MyConnection;

MyConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; data source=C:\myData.XLS; Extended Properties=Excel 8.0;");

// Select the data from Sheet1 of the workbook.
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);

// READ from Excel DB
DS = new DataSet();
MyCommand.Fill(DS);
MyConnection.Close();

// Write to Excel DB
MyCommand = new System.Data.OleDb.OleDbDataAdapter(insert into [Sheet1$] ([CLIENTS], [ASSIGNMENTS], [STATUS]) values( '" + cbClient.Text + "', '" + cbAssignment.Text + "', 'PAUSED')", MyConnection);


So as previouslly mentioned this code READS values from my Excel File correctly (DataSet ds is properly populated) HOWEVER it doesn't seem to WRITE (the INSERT INTO). Don't get me wrong - this doesn't generate any errors and seems to execute fine BUT it doesn't actually make/save the changes to the EXCEL (.xls) file. IS there something I am missing? Do I need to confirm/save the changes? Am I missing something with my MyCommand.?? Commit changes?
Any help/hints would be GREATLY appreciated. Thanks,

klintan
September 6th, 2005, 08:59 AM
DataAdapters takes a select statement in their constructor - you are passing an insert statement.

Also DataAdapters are not commands, so naming a DataAdapter variable myCommand can be a bit confusing.

You should either:

- Create an insert command and add it to your data adapter, and use the data adapter to update your data source from the data set

- Create an insert command and use it to update your data source directly (write code that gets some data from a data set, some controls, or some other variables, submits that data to parameters of the command, and then execute the command)