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

来源:互联网 发布:生死狙击矩阵视频 编辑:程序博客网 时间:2024/05/16 05:59
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;        }

0 0