将列表框项目保存到csv文件中

时间:2019-04-05 15:25:05

标签: c#

我有一个包含学生信息的列表框,其中有一个学生ID和一个学生标记,当我写入文件时,我希望该学生ID和StudentMark在不同的列中(例如,第一个学生ID将在A1中并且他们的标记将在B1中。依此类推,直到所有学生都写入文件中为止。

我有这段代码,但是这段代码仅将student信息添加到一列中,我将如何将其拆分为数据并将其分为两列

if(lstMarks.Items.Count > 0)
            {
                using(TextWriter outputfile = new StreamWriter("StudentRecords.csv"))
                {
                    foreach(string data in lstMarks.Items)
                    {
                        outputfile.WriteLine(data);
                    }
                    MessageBox.Show("Student Information inserted successfully"); 
                }
            }

2 个答案:

答案 0 :(得分:0)

您可以在foreach循环中创建一个字符串和WriteLine

您将必须拆分字符串,以便数组中有studentIdstudentMark。然后,您可以构建一个用逗号分隔的字符串。 最后使用flush清除所有缓冲区

using(TextWriter outputfile = new StreamWriter("StudentRecords.csv"))
{
    foreach(string data in lstMarks.Items)
    {
        var dataArray = data.split(':');
        var line = string.Format("{0},{1}", data[0] , data[1]);
        outputfile.WriteLine(line);
        outputfile.Flush();
    }
    MessageBox.Show("Student Information inserted successfully"); 
}

答案 1 :(得分:0)

这将满足您的需求...

outputfile.WriteLine(string.Join(",", data.Split(':')));

这首先是将字符串data拆分到找到冒号的位置,然后返回一个数组。然后string.Join()使用逗号作为分隔符,将该数组作为字符串重新连接在一起。

您也可以使用data.Replace(":", ",")