小编典典

将DataTable转换为CSV流

c#

当前有一个DataTable,但希望通过WebHandler将其流式传输给用户。FileHelpersCommonEngine.DataTableToCsv(dt, "file.csv")。但是它将保存到文件中。如何将其保存到流中?当我知道高级列或它们不变时,我知道该怎么做,但是我想直接从数据表中生成列标题。

如果我知道这些列,就可以创建类:

[DelimitedRecord(",")]
public class MailMergeFields
{
    [FieldQuoted()]
    public string FirstName;
    [FieldQuoted()]
    public string LastName;
}

然后使用FileHelperEngine并添加记录:

FileHelperEngine engine = new FileHelperEngine(typeof(MailMergeFields));

MailMergeFields[] merge = new MailMergeFields[dt.Rows.Count + 1];

// add headers
merge[0] = new MailMergeFields();
merge[0].FirstName = "FirstName";
merge[0].LastName = "LastName";

int i = 1;              
// add records
foreach (DataRow dr in dt.Rows)
{
    merge[i] = new MailMergeFields();
    merge[i].FirstName = dr["Forename"];
    merge[i].LastName = dr["Surname"];
    i++;
}

最后写入流:

TextWriter writer = new StringWriter();
engine.WriteStream(writer, merge);
context.Response.Write(writer.ToString());

不幸的是,由于我之前不知道各列,因此无法提前创建类。


阅读 401

收藏
2020-05-19

共1个答案

小编典典

您可以自己快速写一些东西:

public static class Extensions
{
    public static string ToCSV(this DataTable table)
    {
        var result = new StringBuilder();
        for (int i = 0; i < table.Columns.Count; i++)
        {
            result.Append(table.Columns[i].ColumnName);
            result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
        }

        foreach (DataRow row in table.Rows)
        {
            for (int i = 0; i < table.Columns.Count; i++)
            {
                result.Append(row[i].ToString());
                result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
            }
        }

        return result.ToString();
    }
}

并测试:

  public static void Main()
  {
        DataTable table = new DataTable();
        table.Columns.Add("Name");
        table.Columns.Add("Age");
        table.Rows.Add("John Doe", "45");
        table.Rows.Add("Jane Doe", "35");
        table.Rows.Add("Jack Doe", "27");
        var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(table.ToCSV());
        MemoryStream stream = new MemoryStream(bytes);

        StreamReader reader = new StreamReader(stream);
        Console.WriteLine(reader.ReadToEnd());
  }

编辑:关于您的评论:

这取决于您要csv格式化的方式,但是通常情况下,如果文本包含特殊字符,则要用双引号将其括起来,即:“
my,text”。您可以在创建csv的代码中添加检查以检查特殊字符,如果有的话,则将文本用双引号引起来。至于.NET
2.0,只需在您的类中将其创建为帮助方法,或在方法声明中删除this并按如下方式调用它即可:Extensions.ToCsv(table);

2020-05-19