Friday, March 27, 2009

How to open Excel XLS file in C#.net

Suppose you have an excel file that contains the data and you wish to use the same The following code snippet will read the file and return it in a dataset now you are free to use this dataset for your purpose.



static DataSet readExcel()
{
string filename = "";
string sheetname = "";
filename = "";
sheetname = "";
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0");
con.Open();
DataSet myDataSet = new DataSet();
OleDbDataAdapter myCommand = new OleDbDataAdapter(" SELECT * FROM ["+sheetname+"$]", con);
myCommand.Fill(myDataSet);
con.Close();
return myDataSet;
}