转换数据表到CSV流 [英] Convert DataTable to CSV stream

查看:130
本文介绍了转换数据表到CSV流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前有一个DataTable,但希望通过WebHandler将其传输到用户。 FileHelpers 具有 CommonEngine.DataTableToCsv(DTFILE.CSV)。然而,它保存到一个文件中。我怎样才能将其保存到一个流呢?我知道如何做到这一点的时候,我知道在先进的列或他们不改变,但我想从数据表生成连续的列标题。

Currently have a DataTable, but wish to stream it to the user via a WebHandler. FileHelpers has CommonEngine.DataTableToCsv(dt, "file.csv"). However it saves it to a file. How can I save it to a stream instead? I know how to do it when I know the columns in advanced or they don't change, but I want to generate the column headings straight from the data table.

如果我知道我的列刚创建类:

If I know the columns I just create the class:

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

然后使用FileHelperEngine并添加记录:

Then use FileHelperEngine and add the records:

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());

不幸的是,因为我不知道前手的列,我不能用手之前创建的类。

Unfortunately as I don't know the columns before hand, I can't create the class before hand.

推荐答案

您可以只写东西很快自己:

You can just write something quickly yourself:

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());
  }

编辑:回复您的意见:

Re your comments:

这取决于你希望你的CSV格式但是总的来说,如果文本包含特殊字符,你想它括在双引号,即:我,文本。您可以在code创建的CSV检查特殊字符,并且包围在双引号中的文本,如果它是补充检查。而对于.NET 2.0的东西,只是将其创建为在你的类一个helper方法或删除这个字在方法声明中并调用它像这样:Extensions.ToCsv(表);

It depends on how you want your csv formatted but generally if the text contains special characters, you want to enclose it in double quotes ie: "my,text". You can add checking in the code that creates the csv to check for special characters and encloses the text in double quotes if it is. As for the .NET 2.0 thing, just create it as a helper method in your class or remove the word this in the method declaration and call it like so : Extensions.ToCsv(table);

这篇关于转换数据表到CSV流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆