출처: http://www.c-sharpcorner.com/uploadfile/hrojasara/export-gridview-data-in-csv-format/

아주 좋은 것을 구글에서 찾았다.
아주 쉽게 csv 파일로 저장되게 되어 있어서 문제가 발생하지 않았다.

다른 소스들은 datagridview가 여러 페이지로 되어 있으면 중간에 에러가 발생했는데,
이것은 그냥 첫 페이지(보이는 페이지)만 저장하였다.

이것은 내부적으로 다시 쿼리를 넣어서 처리하면 되니 크게 문제되지 않는다.

잘 사용해보시길... 많은 도움이 된 소스이다.

Thank you


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.

Posted by 노을지기