使用 StreamWriter 将 headers 添加到 CSV 输出文件中

Adding headers into CSV output file using StreamWriter

我正在尝试将 headers 添加到 CSV 文件中,作为 headers 我希望在 WriteLine.

中使用变量名称

这是我的代码:

using (StreamWriter file = new StreamWriter(fs))                    
{
    for (int s = 0; s < pr.Length; ++s)
    {
        string[] UsersIDS = new string[] {""};
        UsersIDS = db.GetUsersList(pr[s].ProjectID);
        file.WriteLine(
             pr[s].ProjectID + '"' + ',' + 
             '"' +  pr[s].ProjectTitle + '"' + ',' + 
             pr[s].PublishStatus + '"' + ',' + 
             UsersIDS.Length); 
    }
}

只是普通的 WriteLine 和常量字符串似乎就是你想要的(除非你想通过反射或其他方式获取列名):

using (StreamWriter file = new StreamWriter(fs))                    
{
    file.WriteLine( "ProjectID,ProjectTitle,PublishStatus,UsersIDS_Length"); 

    for (int index = 0; index < pr.Length; index++)
    {
        var usersIds = db.GetUsersList(pr[s].ProjectID);
        file.WriteLine("{0},\"{1}\",{2},{3}",
           pr[s].ProjectID, pr[s].ProjectTitle,
           pr[s].PublishStatus, usersIds.Length); 
    }
}

(听起来你还想在标题周围加上引号……其余的引号看起来不平衡)。

我建议你做以下修改

using (StreamWriter file = new StreamWriter(fs))                    
{
    file.WriteLine("ProjectID, ProjectTitle,PublishStatus,Length");
    for (int s = 0; s < pr.Length; ++s)
    {
        string[] UsersIDS = new string[] {""};
        UsersIDS = db.GetUsersList(pr[s].ProjectID);
        file.WriteLine( pr[s].ProjectID + '"' + ',' + '"' + pr[s].ProjectTitle + '"' + ',' + pr[s].PublishStatus + '"' + ',' + UsersIDS.Length); 

}//end of for