.net 保存datatable保存成csv文件

View Code
/// <summary>
/// 将DataTable中数据写入到CSV文件中
/// </summary>
/// <param name="dt">提供保存数据的DataTable</param>
/// <param name="msg">尾行数据</param>
/// <param name="fileName">CSV的文件路径</param>
public static void SaveCSV(DataTable dt, string msg, string fileName)
{
FileStream fs = new FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
string data = "";
#region dt写入
//写出列名称
for (int i = 0; i < dt.Columns.Count; i++)
{
data += dt.Columns[i].ColumnName.ToString();
if (i < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);


//写出各行数据
for (int i = 0; i < dt.Rows.Count; i++)
{
data = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
data += dt.Rows[i][j].ToString();
if (j < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
}
#endregion
#region msg写入
data = msg;

sw.WriteLine(data);


#endregion
sw.Close();
fs.Close();
}

直接贴上代码了,自己看看说明。

posted @ 2012-01-29 13:53  随风ˇ止步  阅读(1261)  评论(0编辑  收藏  举报