使用StreamWriter将标头添加到CSV输出文件

问题描述:

我试图添加头文件到CSV文件中,作为头文件,我想在 WriteLine 中使用变量名称。

I am trying to add headers into the CSV file and as a headers I would like to have the variables names used in the 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); 
    }
}


I建议您修改

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