Converting DataSet/DataTable to CSV

后端 未结 5 488
梦谈多话
梦谈多话 2020-12-11 07:09

Please let me know, if there any way to generate CSV files from a DataTable or DataSet? To be specific, without manually iterating through rows of DataTable and concatenatin

5条回答
  •  臣服心动
    2020-12-11 07:31

    A relative simple, compact and quite flexible solution could be the following extension method:

    public static string ToCsv(this DataTable table, string colSep = "", string rowSep = "\r\n")
    {
        var format = string.Join(colSep, Enumerable.Range(0, table.Columns.Count)
                                                .Select(i => string.Format("{{{0}}}", i)));
    
        return string.Join(rowSep, table.Rows.OfType()
                                            .Select(i => string.Format(format, i.ItemArray)));
    }
    

    Please note that this solution could cause problems with huge amounts of data, in which case you should stream the output. Quoting and formatting would of course make the code more complex.

提交回复
热议问题