使用C#中的CsvHelper写入CSV文件

时间:2018-03-22 16:11:55

标签: c# csv csvhelper

我尝试使用C#中的CsvHelper写入CSV文件。 这是图书馆http://joshclose.github.io/CsvHelper/的链接 没有任何内容发送到csv文件。我试着做“exportCsv.WriteField("Hello");”,但仍然没有发生任何事情。

List<string> ColumnOne = new List<string>();
List<string> ColumnTwo = new List<string>();
var csvTextWriter = new 
    StreamWriter(@"C:\Users\Public\Documents\ExportTest.csv");
var exportCsv = new CsvWriter(csvTextWriter);
    //creating a list to store workflows then adding name and description to the myWorkflowsList list
   if (myWorkflows.WorkFlowCollection.Any())
   {
        foreach (var Workflow in myWorkflows.WorkFlowCollection)
        {
                    ColumnOne.Add(Workflow.WorkflowName);
                    ColumnTwo.Add(Workflow.WorkflowDescription);
        }
        exportCsv.WriteField(ColumnOne);
        //exportCsv.WriteField(ColumnTwo);
        exportCsv.NextRecord();
        exportCsv.Flush();
        Console.WriteLine("File is saved: 
                C:\\Users\\Public\\Documents\\ExportTest.csv");
        Console.ReadLine();
    }

1 个答案:

答案 0 :(得分:2)

您的代码未添加任何记录。它没有对WriteRecordsWriteRecord的任何来电。看起来它试图将整个字符串列表写入单个字段。

要将两列写入文件,您可以使用`WriteRecords,例如:

var data = from flow in myWorkflows.WorkFlowCollection
           select new { flow.WorkflowName,flow.WorkflowDescription};
using (var writer = new StreamWriter("test.csv"))
using (var csv = new CsvWriter(writer))
{
    csv.WriteRecords(data);
}

这将编写一个包含字段名称WorkflowNameWorkflowDescription

的文件

您可以通过创建一个只接受所需字段的小类来更改字段的写入方式,并通过属性设置名称等:

class Flow
{

    [NameAttribute("Workflow Name")]
    public string WorkflowName { get; set; }
    [NameAttribute("Workflow Description")]
    public string WorkflowDescription { get; set; }

    public Flow(string workflowName, string workflowDescription)
    {
        WorkflowName = workflowName;
        WorkflowDescription = workflowDescription;
    }
}


//...
var data = from flow in myWorkflows.WorkFlowCollection
           select new Flow(flow.WorkflowName,flow.WorkflowDescription);
using (var writer = new StreamWriter("test.csv"))
using (var csv = new CsvWriter(writer))
{
    csv.WriteRecords(data);
}