Writing to an Excel spreadsheet

  • Thread starter Thread starter John S
  • Start date Start date
J

John S

I am trying to write data to an excel spreadsheet from a C# app and
cannot make it work. Does anyone have any good examples? Please do
not include any XML examples.
 
Microsoft has a Sample called 'AutoExcel'...

One way to find it is to launch C# Express
and query help for 'Excel Sample'.

If that fails, perhaps i can post it to a NG where
large posts are tolerable.
--
Grace + Peace,
Peter N Roth
Engineering Objects International
http://engineeringobjects.com
Home of Matrix.NET
 
John,

You can do this a couple of different ways. If you just want to populate an
existing workbook/worksheet you can use the OleDb class to accomplish this.
Just create a datasource to the workbook and open a connection. Now you will
be able to access the sheets in the workbook just like tables. I have
provided an example below to do this.

You can also use the excel object to create the workbook from scratch. I
have pasted a link to the MSDN that details how to do this with Office XP or
Office 2003. If you are using Office XP you can download the PIA to use but
if you are using Excel 2000 you will need to use the tlbimp to generate the
PIA yourself.

I hope this helps
-------------------------------------

//link
http://support.microsoft.com/kb/302084/EN-US/

//code
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data Source=D:\temp\queryExcelTemp.xls;" +
"Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "Insert into [Sheet1$] (FirstName, LastName)" +
" values ('Fred', 'Flintstone')";
cmd.ExecuteNonQuery();
cmd.CommandText = "UPDATE [Sheet1$] SET FirstName = 'Homer', LastName =
'Simpson' " + " WHERE FirstName = 'Joe'";
cmd.ExecuteNonQuery();
conn.Close();
 
Interesting! MS's example accesses Excel
directly thru interop.

Thanks for teaching me something new.
--
Grace + Peace,
Peter N Roth
Engineering Objects International
http://engineeringobjects.com
Home of Matrix.NET


Brian Brown said:
John,

You can do this a couple of different ways. If you just want to populate
an
existing workbook/worksheet you can use the OleDb class to accomplish
this.
[ ]
 
Back
Top