使用Winforms导出为CSV(内置)

时间:2010-07-18 11:32:26

标签: winforms csv

有没有办法使用.NET 2.0 Winforms实现从数据网格导出csv?

由于

1 个答案:

答案 0 :(得分:2)

没有任何内置,但你自己做起来相当简单。

// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter("~/GridData.txt", false);

DataTable dt = GetDataTable(); // Pseudo code

// First we will write the headers.
sw.WriteLine(string.Join(",", dt.Columns.Select(c => c.ColumnName)));

// Now write all the rows.
int iColCount = dt.Columns.Count;
foreach (DataRow dr in dt.Rows)
{
    List<string> columnData = new List<string>();
    for (int i = 0; i < iColCount; i++)
    {
        if (!Convert.IsDBNull(dr[i]))
        {
            columnData.Add(dr[i].ToString());
        }
        else
        {
            columnData.Add(string.Empty);
        }
    }
    sw.WriteLine(string.Join(",", columnData.ToArray()));
}

sw.Close();

可以对此代码进行进一步的优化和改进。我对写出行的代码不满意。