0

I am looping my table data and trying to place table rows in excel file but I need to get index of each row in order to make rows in my excel file.

foreach (DataRow row in dt.Rows)
{
  xlWorkSheet.Cells[2, 1] = row["Id"].ToString();
  xlWorkSheet.Cells[2, 2] = row["ProductId"].ToString();
  xlWorkSheet.Cells[2, 3] = row["OrderQuantity"].ToString();
  xlWorkSheet.Cells[2, 4] = row["CustomerID"].ToString();
  xlWorkSheet.Cells[2, 5] = row["OrderDate"].ToString();
  xlWorkSheet.Cells[2, 6] = row["Tax"].ToString();
  xlWorkSheet.Cells[2, 7] = row["Total"].ToString();
  xlWorkSheet.Cells[2, 8] = row["Net"].ToString();
}

All I need is the way to replace 2 (excel row number) in xlWorkSheet.Cells[2, 8] with foreach index number so instead of static row 2 it will be row 3, 4,5,6,... based on how many rows I have in database.

Any suggestion?

mafortis
  • 6,750
  • 23
  • 130
  • 288
  • 2
    use a local variable declared outside the loop and incremented inside it or switch to a for loop for(int i = 0; i < dt.Rows.Count; i++){} – T.Schwarz Jul 21 '21 at 08:17
  • Does this answer your question? [How do you get the index of the current iteration of a foreach loop?](https://stackoverflow.com/questions/43021/how-do-you-get-the-index-of-the-current-iteration-of-a-foreach-loop) – Johnathan Barclay Jul 21 '21 at 08:19
  • @T.Schwarz sorry I didn't understand! then how do I get my `row["Id"]`? – mafortis Jul 21 '21 at 08:19
  • 2
    You might use LINQ: `foreach(var (row,index) in dt.Rows.Select((v,i) => (v,i)))` – SomeBody Jul 21 '21 at 08:21
  • 1
    int rowcount = 0; foreach(DataRow row in dt.Rows){ xlWorkSheet.Cells[rowcount, 1] = row["Id"].ToString(); ....... rowcount++;} – T.Schwarz Jul 21 '21 at 08:21
  • @SomeBody It return error `CS8130` – mafortis Jul 21 '21 at 08:22
  • @T.Schwarz Thank you, now in console it says `Exception thrown: 'System.Runtime.InteropServices.COMException' in mscorlib.dll` – mafortis Jul 21 '21 at 08:24
  • @mjwills `cannot infer the type of implicitly-typed deconstruction variable` – mafortis Jul 21 '21 at 08:25

2 Answers2

1

You can initialize a local variable outside a foreach loop and increment it until last row. This will hold current row. e.g

int i=0; 
foreach (DataRow row in dt.Rows) 
{

xlWorkSheet.Cells[i, 1] = row["Id"].ToString(); 
i++; 
} 
Harkirat singh
  • 599
  • 6
  • 19
0

you can declare an int an increment that with every iteration. For example (dummy code):

    int count = 0;
    foreach (DataRow row in dt.Rows)
    {
      xlWorkSheet.Cells[count, 1] = row["Id"].ToString();
      ...
      xlWorkSheet.Cells[count, 8] = row["Net"].ToString();
      count ++;
    }

You can of course initialize the value of count from 2 if that suits your needs. It will just increment it.