简体   繁体   中英

Adding headers into CSV output file using StreamWriter

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 .

Here you have my code:

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); 
    }
}

Just regular WriteLine with constant string seem to be what you are after (unless you want to get names of columns via reflection or some other way):

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); 
    }
}

(Sound like you also wanted quotes around title... the rest of quotes looked unbalanced).

I propose you following modification

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM