在C#中如何将SQL Server数据库的表格中数据导出形成.csv文件,应该如何编程呀,求详解数据库编程C#SQL Server

解决方案 »

  1.   

    导出成excel
      

  2.   

    csv一般用逗 分隔字段第一行为一条记录 换行用\r\n。
    字段包含逗号还有一些不记得了,用双引号包字段引起来就好了。写入到文本文件中反缀改成csv即可。
      

  3.   

    你用记事本打开csv格式的文件就知道了
      

  4.   

    有时候用的几个方法。        static char  delimiter = ',';
            static string CRLF = "\r\n";
           public static void WriteCsvFile(DataTable dt,string fileName)
            {
                StringBuilder sb = new StringBuilder();
     
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (i == 0)
                    {
                        sb.Append(dt.Columns[i].ColumnName);
                    }
                    else
                    {
                        sb.Append(delimiter);
                        sb.Append(dt.Columns[i].ColumnName);
                    }
                }            foreach (DataRow dr in dt.Rows)
                {
                    sb.Append(CRLF);
                    for (int colIndex = 0; colIndex < dt.Columns.Count; colIndex++)
                    {
                            if (colIndex == 0)
                            {
                                sb.Append(EescapeCsv(dr[colIndex]));
                            }
                            else
                            {
                                sb.Append(delimiter);
                                sb.Append(EescapeCsv(dr[colIndex]));
                            }
                    }
                }            WriteCsvFile(fileName, sb);
            }        public static void WriteCsvFile( string fileName, StringBuilder text)
            {
                using (StreamWriter write = new StreamWriter(fileName, false, Encoding.Unicode))
                {
                    write.Write(text);
                    write.Close();
                }
            }
                   public static string EescapeCsv(string text)
            { 
                if (!string.IsNullOrEmpty(text))
                {                if (text.Contains("\""))
                    {
                        text = text.Replace("\"", "“");
                    }                if (text.Contains(",")  || text.Contains("\n") || text.Contains("\r\n"))
                    {
                        text = string.Concat("\"", text, "\"");
                    }            }
                return text;
            }
        }