I am reading an Excel document grid (Matrix) cell by cell in order to write them in another Excel document. The reading is done starting from a specific cell at some position and stops at some other specific position for example from cell A3 to A5 for 4 rows to get a matrix of cells. Now i want to rewrite these cells in the exact order they are in except that i want to reinitialize the start to be at the origin of the destination Excel document. I am trying with the following code :
int l=1;
int m=1;
for (int i = n1; i <= n2; i++)
{
l++;
for (int j = n3; j <= n4; j++)
{
m++;
if (xlRange.Cells[i, j] != null && ((Excel.Range)xlRange.Cells[i, j]).Value2 != null)
{
l = i; // these indices should be altered in order to write at the origin
m = j; // these indices should be altered in order to write at the origin
// Write at the destination Excel document worksheet (xlWorksheet2)
xlWorksheet2.Cells[l,m] = ((Excel.Range)xlRange.Cells[i, j]).Value2.ToString();
}
}
}
To note that both n1
could be equal to n2
and n3
could be equal to n4
.
My solution does not bring the start of the reading grid to the origin when writing to the destination Excel document. My question is how to define the indices of the array in order to write starting from while keeping the order of the cells as is.
UPDATE : using @Caius Jard suggested solution i get the following results in the destination Excel document :