本文介绍了将数据写入 CSV 时如何排除标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将我的数据从 public class 写入 CSV 文件.因为我想附加我的数据,所以我想排除头文件的导入,只从类中导入数据.我下面的代码同时导入标题和数据.希望得到帮助.谢谢.

I am writing my data from a public class to a CSV file. As I want to append my data, I want to exclude the importing of header and only import the data from the class. My code below imports both headers and data. Hope to get help. Thanks.

Record.cs - 我的班级

public class Record
{
    public string Name
    {
        get; set;
    }

    public DateTime DateOfBirth
    {
        get; set;
    }
}

Form1.cs - 我的表单

public partial class Form1 : Form
{
    private List<Record> records;

    public Form1()
    {
        InitializeComponent();
        records = new List<Record>();
    }

    private void Savetocsv_Click(object sender, EventArgs e)
    {
        var myDocument = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        using (var writer = new StreamWriter(myDocument + "/my-data.csv", append: true))
        {
            using (var csv = new CsvWriter(writer))
            {
                csv.WriteRecords(records);
            }
        }
    }

推荐答案

使用 Configuration ,你可以使用属性 HasHeaderRecord:

HasHeaderRecord :获取或设置一个值,该值指示 CSV 文件是否具有标题记录.
默认为真.

var records = new List<Foo>
{
    new Foo { Id = 1, Name = "one" },
    new Foo { Id = 1, Name = "one" },
};

using (var writer = new StreamWriter($"file.csv"))
using (var csv = new CsvWriter(writer, new Configuration { HasHeaderRecord = false }))
{
    csv.WriteRecords(records);
}

结果文件:file.csv"

Result file : "file.csv"

1;一个
1;一

或者简单地循环记录并写入它们:

Or simply loop on records an write them:

var records = new List<Foo>
{
    new Foo { Id = 1, Name = "one" },
    new Foo { Id = 1, Name = "one" }
};

using (var writer = new StreamWriter($"file.csv"))
using (var csv = new CsvWriter(writer))
{
    foreach (var record in records)
    {
        csv.WriteRecord(record);
        csv.NextRecord();
    }
}

这篇关于将数据写入 CSV 时如何排除标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 05:08