我正在尝试将标头添加到CSV文件中,作为标题,我希望在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);
}
}
答案 0 :(得分:1)
使用常量字符串的常规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);
}
}
(听起来你也想在标题周围引用...其余的引号看起来不平衡。)
答案 1 :(得分:1)
我建议您进行以下修改
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