DataGrid到CSV文件

时间:2011-08-17 09:31:03

标签: c# asp.net .net-3.5 datagrid csv

我将DataTable绑定到DataGrid,一切正常。 我的下一步是将 DataGrid数据导出为CSV 文件,逗号分隔。

使用 ASP.Net 3.5 执行此操作的最佳/最简单方法是什么?

1 个答案:

答案 0 :(得分:8)

我使用此代码段将DataGrid导出为CSV。也许有帮助:

public void OnExportGridToCSV(object sender, System.EventArgs e)
{
    // Create the CSV file to which grid data will be exported.
    StreamWriter sw = new StreamWriter(Server.MapPath("~/GridData.csv"), false);
    // First we will write the headers.
    DataTable dt = ((DataSet)grid1.DataSource).Tables[0];

    int iColCount = dt.Columns.Count;
    for (int i = 0; i < iColCount; i++)
    {
        sw.Write(dt.Columns[i]);
        if (i < iColCount - 1)
        {
            sw.Write(",");
        }
    }
    sw.Write(sw.NewLine);
    // Now write all the rows.
    foreach (DataRow dr in dt.Rows)
    {
        for (int i = 0; i < iColCount; i++)
        {
            if (!Convert.IsDBNull(dr[i]))
            {
                sw.Write(dr[i].ToString());
            }
            if (i < iColCount - 1)
            {
                sw.Write(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator);
            }
        }
        sw.Write(sw.NewLine);
    }
    sw.Close();
}