正在从C#写入csv文件

本文关键字:csv 文件 写入 | 更新日期: 2023-09-27 17:58:38

我将插入到文本文件中的代码如下:

foreach (var kvauthor in _tauthorData)
{
   foreach (var coAuthor in kvauthor.Value.CoAuthors)
   {
      twObjClus.WriteLine("AuthorID: {0}, AuthorName: {1}, ClusterID: {2}, PaperID: {3},  
                           CoAuthors: {4}, PaperCategory: {5}, Venue: {6}, Year: {4}",  
                           eAuthor.AuthorID, eAuthor.AuthorName, curCluster.GetClusterID(),  
                           kvauthor.Key, coAuthor, kvauthor.Value.PaperCategory,  
                           kvauthor.Value.VenueID, kvauthor.Value.Year);
   }
}  

我想把所有这些数据插入一个csv文件,而我已经尝试过了:

var csv = new StringBuilder();  
foreach (var kvauthor in _tauthorData)
{
   foreach (var coAuthor in kvauthor.Value.CoAuthors)
   {
      csv.AppendFormat("{0},{1},{2},{3},{4},{5},{6}",AuthorID: {0}, AuthorName: {1}, ClusterID: {2}, PaperID: {3},  
                           CoAuthors: {4}, PaperCategory: {5}, Venue: {6}, Year: {4}",  
                           eAuthor.AuthorID, eAuthor.AuthorName, curCluster.GetClusterID(),  
                           kvauthor.Key, coAuthor, kvauthor.Value.PaperCategory,  
                           kvauthor.Value.VenueID, kvauthor.Value.Year);
   }
}  

如何将此数据逐行插入到带有列标题的csv文件中?

正在从C#写入csv文件

添加列标题很简单,只需执行一次即可(当打开文件或创建稍后将用于添加行的StringBuilder实例时)。

var csv = new StringBuilder();  
// add column headers first
csv.AppendLine("AuthorID,AuthorName, ..."); // and so on
// add data
foreach (var kvauthor in _tauthorData)
    foreach (var coAuthor in kvauthor.Value.CoAuthors)
    {
        csv.AppendLine($"{coAuthor.AuthorId},{coAuthor.Name}, ..."); // and so on
        // if you don't have C# 6.0
        // csv.AppendFormat("{0},{1}, ... {N}", coAuthor.AuthorId, coAuthor.Name, ..., Environmental.NewLine");
    }
File.WriteAllText(path, csv.ToString());

注意:您可以使用AppendLine自动添加Environmental.NewLine,否则(如果使用AppendFormat)手动将其添加到string的末尾。