0

im exporting a gridview table to Microsoft Excel using this code :

private void button5_Click(object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Excel.Application Excel = new     Microsoft.Office.Interop.Excel.Application();
        Workbook wb = Excel.Workbooks.Add(XlSheetType.xlWorksheet);
        Worksheet ws = (Worksheet)Excel.ActiveSheet;
        Excel.Visible= true;
        ws.Cells[1, 1] = "VehiclePlateNumber";
        ws.Cells[1, 2] = "VehicleDescription";
        ws.Cells[1, 3] = "Distance";

        for (int j = 2; j <= datagridview1.Rows.Count; j++)
        {

            for (int i = 2; i <= 3; i++)

            {
                ws.Cells[j, i] = datagridview1.Rows[j - 2].Cells[i - 1].Value;
            }

}

its working, but the first column is showing only the header text without data, i dont know what is the problem, and i tried to do some changes to the code but i couldn't reach the solution, any help please ?

3 Answers3

0

They way you set the for loops results in looping only in two colums (i=2 ;i<=3) and you also miss the final row. Also in your code you are missing a closing parenthesis.

Try:

 for (int j = 0; j < datagridview1.Rows.Count; j++)
        {   
            for (int i = 0; i < 3; i++)  
            {
                ws.Cells[j, i+1] = datagridview1.Rows[j].Cells[i].Value;
            }
        }
apomene
  • 14,282
  • 9
  • 46
  • 72
0

I think apomene is almost right.

ws.Cells[j +1 , i+1] = datagridview1.Rows[j].Cells[i].Value;

As for some reason excel is not zero based. The only difference is +1 after the j.

Tasos K.
  • 7,979
  • 7
  • 39
  • 63
Catwood
  • 157
  • 7
0

problem is solved after using this code :

for (int j = 2; j <= datagridview1.Rows.Count; j++)
{
for (int i = 1; i <= 3; i++)
{
ws.Cells[j, i] = datagridview1.Rows[j - 2].Cells[i - 1].Value;
}
}
}