Posts

Showing posts with the label excel

Updated getting data from an Excel file in C#

Ok I posted how to get data from an excel file a bit ago. I have some update code that reads all files into a dataset, or reads from a specific file. You could easily modify this code to read from a specific sheet as well. public static DataSet GetAllSheetsFromExcelFile( string filename ) { DataSet ds; try { ds = new DataSet(); DataTable dtSheets = new DataTable(); // get a datatable with the worksheet name(s) OleDbConnection con = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0" ); con.Open(); // get a datatable of the sheetnames in this file DataTable dtNames = con.GetOleDbSchemaTable( System.Data.OleDb.OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" } ); // add each sheet as a new table to our dataset foreach( DataRow row in dtNames.Rows ) { DataTable dtTemp = new DataTable(); ...

Reading from an excel file with C#

Ok so I have found a need to read data from an excel spreadsheet in a C# program. After looking over using COM and other things I found actually OleDB is the best way. This ensures you don't have to have excel/office installed on the target system. It may mean a bit more work but for most purposes I think it is good enough. All of this code is contained in the System.Data.OleDb namespace. This code reads from a known file with a known sheet name. If you want to be more flexible and don't know the sheet name(s) you have to do a bit more magic. That will be covered in another post. From the posts below I have decided a bit more information is necessary for this post to be more informative. When dealing with any office component you have to deal with the different versions (2000,2003,2007) etc. This example is connecting to an excel 2003 file. You will need to use the right excel version number based on what you have installed or what your customers will have installed. ...