Export Gridview Data in .csv Format

Here I will show how you can generate csv file from the grid view in ASP.NET.

Screenshot

CSV File

Output

Output

Code and explanation

// On generate CSV button click
protected void Button1_Click2(object sender, EventArgs e)
{
    // Create a file gridview.csv in writing mode using StreamWriter
    StreamWriter sw = new StreamWriter("c:\\gridview.csv");
    
    // Add the GridView header in CSV file, separated by "," delimiter except the last one
    for (int i = 0; i < GridView1.Columns.Count; i++)
    {
        sw.Write(GridView1.Columns[i].HeaderText);
        if (i != GridView1.Columns.Count - 1)
        {
            sw.Write(",");
        }
    }
    
    // Add a new line
    sw.Write(sw.NewLine);
    
    // Iterate through all the rows within the GridView
    foreach (GridViewRow dr in GridView1.Rows)
    {
        // Iterate through all columns of a 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 - 1)
            {
                sw.Write(",");
            }
        }
        
        // Write new line
        sw.Write(sw.NewLine);
    }
    
    // Flush from the buffers
    sw.Flush();
    
    // Close the file
    sw.Close();
}

Hope you understand it.

Thank you!


Similar Articles