DataReader to .CSV with column names

前端 未结 5 989
清酒与你
清酒与你 2020-12-15 10:49

I\'m generating a csv file from an SqlDataReader, however it is not writing the column names, how can I make it write them? The code I\'m using is as follows:



        
5条回答
  •  孤街浪徒
    2020-12-15 11:16

    Using this solution i created an extension.

    /// 
    /// 
    /// 
    /// 
    /// 
    /// if null/empty will use IO.Path.GetTempPath()
    /// will use csv by default
    public static void ToCsv(this IDataReader reader, string filename, string path = null, string extension = "csv")
    {
        int nextResult = 0;
        do
        {
            var filePath = Path.Combine(string.IsNullOrEmpty(path) ? Path.GetTempPath() : path, string.Format("{0}.{1}", filename, extension));
            using (StreamWriter writer = new StreamWriter(filePath))
            {
                writer.WriteLine(string.Join(",", Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList()));
                int count = 0;
                while (reader.Read())
                {
                    writer.WriteLine(string.Join(",", Enumerable.Range(0, reader.FieldCount).Select(reader.GetValue).ToList()));
                    if (++count % 100 == 0)
                    {
                        writer.Flush();
                    }
                }
            }
    
            filename = string.Format("{0}-{1}", filename, ++nextResult);
        }
        while (reader.NextResult());
    }
    

提交回复
热议问题