csvhelper在最后一个添加新列
编辑,感谢您使用CSVHelper的建议,这实际上有很大帮助。
我所做的是创建一种类似的新方法:
public static void AppendFile<T>(FileInfo fi, List<T> report)
{
var settings = new CsvConfiguration(new CultureInfo("en-GB"))
{
//Delimiter = ";"
};
using var stream = File.Open(fi.FullName, FileMode.Append);
using var writer = new StreamWriter(stream);
using (var csv = new CsvWriter(writer, settings))
{
csv.WriteRecords(report);
}
}
并在CSVhelper网站上浏览示例,创建一个新类:
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
创建一个新列表:
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
并将其称为:
AppendToFile.AppendFile(exportFile, records1);
然后 ,而是在最后一列旁边添加新列,它们在文件的底部添加。
为了澄清,
我要做的是:
我得到的:
您可以看到,它只是被添加为新行而不是除了单独的列,我需要更改什么?
Edit, thank you for the suggestion of using csvhelper, this is actually helping quite a lot.
What I have done is create a new method like so:
public static void AppendFile<T>(FileInfo fi, List<T> report)
{
var settings = new CsvConfiguration(new CultureInfo("en-GB"))
{
//Delimiter = ";"
};
using var stream = File.Open(fi.FullName, FileMode.Append);
using var writer = new StreamWriter(stream);
using (var csv = new CsvWriter(writer, settings))
{
csv.WriteRecords(report);
}
}
And gone through the example on the csvhelper site, creating a new class:
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
and then creating a new list:
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
and calling it like so:
AppendToFile.AppendFile(exportFile, records1);
This is working better than what I had before but, instead adding the new columns beside the last column, they are getting added at the bottom of the file.
For clarification,
what I'm trying to do:
what I'm getting:
As you'll be able to see, it's just being added as new rows rather than being separate columns, what do I need to change?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以实现目标的另一种方法是使用
csvwriter.writeheader
和csvwriter.writerecord
手工编写每个对象。Another way you can accomplish your goal is to write each object to the row by hand using
csvWriter.WriteHeader
andcsvWriter.WriteRecord
.我设法弄清楚了一种对我有用的方式,可能不是最有效的,但确实有效。
首先,将CSV文件的内容放入数据表中,然后在我需要的新列中添加。然后,我清除数据表中的所有行,然后在中添加新行(通过newRows参数添加被删除的数据),然后将数据词写入CSV文件
I managed to figure out a way that worked for me, might not be the most efficient but it does work.
I start by getting the contents of the csv file into a data table and then adding in the new columns that I need. I then clear all the rows in the datatable and add new ones in (the data that is removed is added back in via the newRows parameter) and then write the datatable to the csv file