0

I need three columns from the datagridview to export to columns a, c, and i in excel. All the data in the dataGridView needs to be visible there, but only the first three rows need to be exported.

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

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    for (int j = 0; j < dataGridView1.Columns.Count; j++)
    {
        if (dataGridView1.Rows[i].Cells[j].Value != null)
        {
            objexcelapp.Cells[i + 11, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
        }
    }

}
Ashkan S
  • 10,464
  • 6
  • 51
  • 80

1 Answers1

0

If you only need the first 3 rows, then count to 3 instead of all rows. I don't understand how you ended up with all rows

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

for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < dataGridView1.Columns.Count; j++)
    {
        if (dataGridView1.Rows[i].Cells[j].Value != null)
        {
            objexcelapp.Cells[i + 11, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
        }
    }

}

Update

To write to excel check this post

Community
  • 1
  • 1
Ashkan S
  • 10,464
  • 6
  • 51
  • 80
  • I stated columns. Thanks, but you didn't answer the question. the troubling part is exporting those columns to certain columns in an excel file. – Greyson Aug 11 '16 at 19:45