简体   繁体   中英

Exporting Gridview table to Excel

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 ?

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;
            }
        }

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.

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;
}
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM