您的位置:首页 > 编程语言 > C#

C#导出DataTable数据到CSV文件中

2015-11-26 13:27 507 查看
public void WriteData(DataTable dt, string path)
{
try
{
System.IO.FileStream fs = new FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("GBK"));
for (int i = 0; i < dt.Columns.Count; i++)
{
sw.Write(dt.Columns[i].ColumnName);
if (i != dt.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.WriteLine("");
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
sw.Write(DelSpecialChar(dt.Rows[i][j].ToString()));
if (j != dt.Columns.Count - 1)
{
sw.Write(",");//分隔符
}
}
sw.WriteLine("");
}
sw.Flush();
sw.Close();
}
catch {}
}

public string DelSpecialChar(string str)
{
string result = str;
string[] strQuota = { "~", "!", "@", "#", "$", "%", "^", "&", "*", "`", ";", "'", ",", ".", "/", "/,", "<", ">", "?" };
for (int i = 0; i < strQuota.Length; i++)
{
if (result.IndexOf(strQuota[i]) > -1)
result = result.Replace(strQuota[i], "");
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: