CSV string handling

后端 未结 13 845
北荒
北荒 2020-12-28 16:44

Typical way of creating a CSV string (pseudocode):

  1. Create a CSV container object (like a StringBuilder in C#).
  2. Loop through the strings you want to ad
13条回答
  •  既然无缘
    2020-12-28 17:13

    I use CSVHelper - it's a great open-source library that lets you generate compliant CSV streams one element at a time or custom-map your classes:

    public string ReturnAsCSV(ContactList contactList)
    {
        StringBuilder sb = new StringBuilder();
        using (StringWriter stringWriter = new StringWriter(sb))
        {
            using (var csvWriter = new CsvHelper.CsvWriter(stringWriter))
            {
                csvWriter.Configuration.HasHeaderRecord = false;
                foreach (Contact c in contactList)
                {
                    csvWriter.WriteField(c.Name);
                }
            }
        }
        return sb.ToString();
    }
    

    or if you map then something like this: csvWriter.WriteRecords(contactList);

提交回复
热议问题