Read Excel sheet

This sample code show how to read xls using c#. First create OledbConnection. Below is code.
Details of code:-
1. where Filename is complete path of xls which u want to read
2. listname is name of sheet whose contents u want to read
3. after opening connection we can fill complete sheet data in dataset ds.
4. inside for loop we are reading each cell's content.


string fileName = "d:\\Testing.xls";
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=Excel 8.0");
string listName = "BAR";
con.Open();
try
{
DataSet ds = new DataSet();
OleDbDataAdapter odb = new OleDbDataAdapter("select * from ["+listName+"$]",con);
odb.Fill(ds);
con.Close();
foreach (DataRow myrow in ds.Tables[0].Rows)
{
Object[] cells = myrow.ItemArray;
foreach (Object cellcontent in cells)
{
string cellText = cellcontent.ToString();
}
}
}
catch (Exception ex)
{

}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: