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 - my class
public class Record
{
public string Name
{
get; set;
}
public DateTime DateOfBirth
{
get; set;
}
}
Form1.cs - my form
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);
}
}
}
When creating the CSV file, by default, the INPUT header is returned. To remove the header, just choose CUSTOM and leave it blank. 09-25-2020 08:17 PM
Initially, create a header in the form of a list, and then add that header to the CSV file using to_csv () method. The following CSV file gfg.csv is used for the operation: The CSV file gfg2.csv is created: Another approach of using DictWriter () can be used to append a header to the contents of a CSV file.
All the methods in the above article are perfectly fine and are used by the Python programmer to skip the header of the CSV file while reading the CSV data. The Pandas library method not only allows us to remove the header of the CSV file data but can also be used to remove other rows if we specify their number or index position to the skiprows.
Using the Configuration , you can use the property HasHeaderRecord: HasHeaderRecord : Gets or sets a value indicating if the CSV file has a header record. Default is true.
Using the Configuration
, you can use the property 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);
}
Result file : "file.csv"
1;one
1;one
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();
}
}
The name of the configuration class has changed.
using (var csv = new CsvWriter(outputStream, new CsvConfiguration(CultureInfo.InvariantCulture)
{
HasHeaderRecord = false
}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With