如何从sql server导出到csv文件

时间:2021-10-14 00:28:29

如何从sql server导出到csv文件,具体代码如下:

private static void WriteHeader(SqlDataReader reader, TextWriter output)
   {
       for (int i = 0; i < reader.FieldCount; i++)
       {
           if (i > 0)
               output.Write(',');
           output.Write(reader.GetName(i));
       }
       output.WriteLine();
   }
 
private static void WriteData(SqlDataReader reader, TextWriter output)
   {
       for (int i = 0; i < reader.FieldCount; i++)
       {
           if (i > 0)
               output.Write(',');
           String v = reader[i].ToString();
           if (v.Contains(',') || v.Contains('\n') || v.Contains('\r') || v.Contains('"'))
           {
               output.Write('"');
               output.Write(v.Replace("\"", "\"\""));
               output.Write('"');
           }
           else
           {
               output.Write(v);
           }
       }
       output.WriteLine();
   }