ARTICLE

Export Gridview data in .csv format

Posted by Hiren Soni Articles | ASP.NET Controls in C# August 20, 2010
Here I will show how you can generate csv file from the gridview in asp.net.
Reader Level:

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'>
Login to add your contents and source code to this article
post comment
     

Pls write explanation at above lines. So visitors can understand easily.

Posted by Abhishek Tiwari Mar 23, 2011
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts