gpt4 book ai didi

c# - 将数据写入 CSV 时如何排除 header

转载 作者:太空宇宙 更新时间:2023-11-03 20:50:57 24 4
gpt4 key购买 nike

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

Record.cs - 我的类(class)

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 : Gets or sets a value indicating if the CSV file has a header record.
Default is true.

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”

1;one
1;one

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

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

关于c# - 将数据写入 CSV 时如何排除 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55332538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com