从C#编写csv文件

时间:2016-07-25 11:08:08

标签: c# file csv text

我将文本代码插入到:

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文件中?

1 个答案:

答案 0 :(得分:0)

添加列标题非常简单,只需执行一次(打开文件或创建例如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, scv.ToString());

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