Home » excel » c# – Parse Excel sheet dynamically (cells range not provided, as the location of data in sheet may dynamically vary)

c# – Parse Excel sheet dynamically (cells range not provided, as the location of data in sheet may dynamically vary)

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am using C#.NET 3.5 in VS2010 on Win 7 machine. I have an Excel sheet and I want to extract the data stored in it. I know how to parse the Excel when given the range of cells. Here we connect using OLEDB, give the SQL command and map this to a DataTable, then access the data.

select * from [sheetname$A2:N50]   

where “sheetname” is the name of Excel sheet and “$A2:N50” is the range of cells.

BUT, BUT, my requirement is totally different.

I can’t hardcode the cell range like above, because the location of data cells may change dynamically. For example: data stored in cell A20 may be changed to C14 in the very next execution.

I need to parse my Excel sheet based on some key word searching. I mean I should search for the keyword “XYZ” and than parse the table just below it. This key word may change its position for every execution.

Since I don’t know the cell range, I can’t even get the Excel data into a DataTable using the above query.

How to&Answers:

Instead of selecting from a cell range you can fill all the data into a datatable and query from that.

DataTable dt = new DataTable();
try
{
   OleDbConnection con = new OleDbConnection(string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=yes;IMEX=1""", excelPath));
   OleDbDataAdapter da = new OleDbDataAdapter("select * from [sheetname$]", con);

   da.Fill(dt);
}
catch (Exception ex)
{
   MessageBox.Show(ex.Message);
   return;
}
//now you can use dt DataTable
foreach (DataRow dr in dt.Rows)
{
  //....
}

hope this helps…