Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need to know how to iterate through excel cells using C#.

I have a Data Table that I use to export data to an existing Excel file. I need to be able to search for values that only equal "tel:" and "email:". These values will only be in the second column in excel.

Here is my code sequence. Please let me know what I am doing wrong or if there is a better way.

C#
int rowNum = 1;

foreach (Microsoft.Office.Interop.Excel.Range cell in ws.Rows[rowNum, 2])
     {
         if (cell.Value = "tel:")
         {
        ws.Rows[rowNum].Delete();
         }
     }
Posted
Updated 24-Jun-15 9:35am
v2
Comments
Ralf Meier 24-Jun-15 14:09pm    
Try to use Cells instead of Rows ...
Maciej Los 24-Jun-15 16:34pm    
Issue description does not correspond to code sample. Please, be more specific and provide more details.
Larminces 11-Aug-15 4:36am    
First regarding the DataTable, how exactly are you exporting it to excel file?
What I was thinking is if these cell value's ("tel:" and "email:") come from database then you could just ignore that DataTable's record when doing an export.
For example you can check out this article about both importing and exporting of DataTable into an Excel, it uses this .NET's excel library.

Second regarding the iteration, you can use the same library to read your excel file with C# and then do an intuitive iteration (just like you do with every other .NET's collection). Here is a diagram of the excel file's model on which you would do your iteration.

here you go

pre requisite- Install AccessDatabaseEngine 2007 or 2007

try
{
string path; // your file path 

oledbConn =
    new OleDbConnection(
        @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path
        + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");

oledbConn.Open();
var cmd = new OleDbCommand();

var ds = new DataSet();
cmd.Connection = oledbConn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELEet1$]"; Name of sheet
var oleda = new OleDbDataAdapter(cmd);
oleda.Fill(ds);

foreach (DataRow row in ds.T??les[0].Rows)
{
    // TODO
}
catch (Exception ex)
{
    // log it
}
finally
{
    oledbConn.Close();
}
 
Share this answer
 
You can also use oledb to read/write cell by cell values instead of using interop(office component).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900