Csv助手。第一个价值正在向右移动

时间:2017-11-17 11:07:14

标签: c# csvhelper

我一直在尝试使用csv帮助程序创建一个简单的csv文件。但是,结果,我得到的并不是我的预期。 由于某些我无法找到的原因,第一个值向右移动并显示为标题。

有人能指出我在这里做错了吗?

public class Record
{ 
    public string Vrm { get; set; }        
    public string Version { get; set; }
    public DateTime Started { get; set; }
    public DateTime? Completed { get; set; }
    public string Status { get; set; }
    public string Comments { get; set; }
}

static void Main(string[] args)
    {
        var source = new List<Record> {
            new Record {

                Status = "Success",
                Version = "enhance",
                Started = DateTime.Parse("2017-11-15 13:27:56.9933333"),
                Completed = DateTime.Parse("2017-11-15 13:27:57.7300000"),
                Vrm = "16aux",
                Comments = "Completed Successfully"
            }
        };

        var month = DateTime.UtcNow.Month;
        var year = DateTime.UtcNow.Year;
        var fileName = $"TestFile_{month}{year}.csv";

        using (var sw = new StreamWriter(fileName))
        {
            var writer = new CsvWriter(sw);

            try
            {
                writer.WriteHeader<Record>();
                foreach (var record in source)
                {
                    writer.WriteField(record.Vrm);
                    writer.WriteField(record.Version);
                    writer.WriteField(record.Started);
                    writer.WriteField(record.Completed);
                    writer.WriteField(record.Status);
                    writer.WriteField(record.Comments);
                    writer.NextRecord();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            var i = sw;
        }            
    }

结果是这样的: Result of only one record

Result with two records

1 个答案:

答案 0 :(得分:3)

阅读http://joshclose.github.io/CsvHelper/writing#writing-all-records

您需要在writer.NextRecord();之后调用writer.WriteHeader<Record>();来提升作者一行。

您也可以使用csv.WriteRecords( records );一次性写入所有数据,而不是通过它们进行预告