Error exporting datagridview to excel C # [duplicated]

1

I have the following error:

  

Unhandled exception of type 'System.ArgumentOutOfRangeException'   in mscorlib.dll

     

Additional information: Index was out of range. Must be non-negative   and less than the size of the collection.

In the following line of code:

   ws.Cells[i + 2, j + 1] = dataGridView2.Rows[i].Cells[j].Value.ToString();

The complete code is as follows:

for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
    ws.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}


// storing Each row and column value to excel sheet
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
    for (int j = 0; j < dataGridView1.Columns.Count; j++)
    {
        ws.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
    }
}
ws.Cells.EntireColumn.AutoFit();

int crow = dataGridView1.Rows.Count; //empezamos donde termino


for (int i = 1; i < dataGridView2.Columns.Count + 1; i++)
{
    ws.Cells[crow, i] = dataGridView2.Columns[i - 1].HeaderText;
}
//empezamos desde crow + 1 y nos movemos dgv2.rows.count filas
for (int i = crow + 1; i < dataGridView2.Rows.Count + crow - 1; i++)
{
    for (int j = 0; j < dataGridView1.Columns.Count; j++)
    {
        ws.Cells[i + 2, j + 1] = dataGridView2.Rows[i].Cells[j].Value.ToString();
    }
}

// sizing the columns
ws.Cells.EntireColumn.AutoFit();

What I want to do is save the data from my datagridview in a single excel sheet.

I have already searched for the error, but I can not find it.

    
asked by oscar ramirez 17.03.2017 в 22:18
source

1 answer

1

In the part where you do the cycle to control the columns with the variable j you still have to subtract 1 from the .Count . The two lines of code should look like this:

for (int j = 0; j < dataGridView1.Columns.Count - 1; j++)
    
answered by 17.03.2017 в 22:51