Export Gridview data in .csv format


Here I will show how you can generate csv file from the gridview in asp.net

Screenshot:

1.gif 

Output:

2.gif 

Code and explanation:

// on generate csv button click
protected void Button1_Click2(object sender, EventArgs e)
{
    // create one file gridview.csv in writing mode using streamwriter
    StreamWriter sw = new StreamWriter("c:\\gridview.csv");
    // now add the gridview header in csv file suffix with "," delimeter except last one
    for (int i = 0; i < GridView1.Columns.Count; i++)
    {
        sw.Write(GridView1.Columns[i].HeaderText);
        if (i != GridView1.Columns.Count)
        {
            sw.Write(",");
        }           
    }
    // add new line
    sw.Write(sw.NewLine);
    // iterate through all the rows within the gridview
    foreach (GridViewRow dr in GridView1.Rows)
    {
        // iterate through all colums of specific row
        for (int i = 0; i < GridView1.Columns.Count; i++)
        {
            // write particular cell to csv file
            sw.Write(dr.Cells[i].Text);
            if (i != GridView1.Columns.Count)
            {
                sw.Write(",");
            }
        }
        // write new line
        sw.Write(sw.NewLine);
    }
    // flush from the buffers.
    sw.Flush();
    // closes the file
    sw.Close();
}

Hope you understand it...

Thank you.

erver'>

Similar Articles