DataTable转为TXT文档

public static void SaveCSV(DataTable dt, string fullPath)
        {
            var fi = new FileInfo(fullPath); if (!fi.Directory.Exists) { fi.Directory.Create(); }
            var fs = new FileStream(fullPath, FileMode.Append, FileAccess.Write);            //StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);            
            var sw = new StreamWriter(fs, Encoding.UTF8);
            var data = "";            //写出列名称           
            if (s == 0)
            {
                ++s;
                for (var i = 0; i < dt.Columns.Count; i++)
                {
                    data += dt.Columns[i].ColumnName;
                    if (i < dt.Columns.Count - 1)
                    {
                        data += ",";
                    }
                }
                sw.WriteLine(data);
            }
            //写出各行数据        
            for (var i = 0; i < dt.Rows.Count; i++)
            {
                data = "";
                for (var j = 0; j < dt.Columns.Count; j++)
                {
                    var str = dt.Rows[i][j].ToString();
                    str = str.Replace("\"", "\"\""); //替换英文冒号 英文冒号需要换成两个冒号   
                    if (str.Contains(',') || str.Contains('"') || str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中          
                    {
                        str = string.Format("\"{0}\"", str);
                    }
                    data += str;
                    if (j < dt.Columns.Count - 1)
                    {
                        data += ",";
                    }
                }
                sw.WriteLine(data);
            }
            sw.Close();
            fs.Close();


        }

非原创

你可能感兴趣的:(DataTable转为TXT文档)