读取CSV时跳过标题

时间:2015-06-25 09:43:15

标签: c# visual-studio csv

我希望能够在读取和写入csv时跳过标题

这是我到目前为止的代码

  try
        {
            using (StreamWriter sw = new StreamWriter(writefilename))// StreamWriter is used to write a text file
            using (StreamReader sr = new StreamReader(readfilename)) // StreamReader is used to read a text file
            {
                //Writing headings to file
                heading = "NI Number,Surname,Forename,Employee,Employer(gross),Contribution Status,Contribution Status Date";
                sw.WriteLine(heading);


                while ((txtline = sr.ReadLine()) != null)  // Reads one line into the variable txtline
                {



                    //spiliting the file into columns if there is something in it.
                    //oldcolumns = txtline.Split(',');

                    oldcolumns = Regex.Split(txtline, ",");

                    //spliting old columns[0] where there is a space and putting it in the names array.
                    //names = Regex.Split(oldcolumns[0],",");
                  string []  names = oldcolumns[0].Split(' ');
                  var result = string.Join(" ", oldcolumns[0].Split(' ').Skip(1));




                    //writing the oldcolumns data into the newcolumns.
                    newcolumns[0] = oldcolumns[1];
                    newcolumns[1] = result;
                    newcolumns[2] = names[0];
                    newcolumns[3] = oldcolumns[9];
                    newcolumns[4] = oldcolumns[11];
                    newcolumns[5] = "";
                    newcolumns[6] = "";


                    //using loop to run through all the columns
                    csvline = "";


                    for (int i = 0; i < 7; i++)
                    {
                        csvline = csvline + "\"" + newcolumns[i].Replace("\"", "") + "\",";
                    }

                    //writing to file.
                    sw.WriteLine(csvline);
                }

据我所知,如果我想跳过一个列,我可以在for循环中执行此操作,但我不知道如何跳过一行。

4 个答案:

答案 0 :(得分:0)

只计算行数和数量忽略它:

for ( int LineNo = 1; ; LineNo++)
{
  ReadLine
  if (LineNo == 1)
    continue
}

(任何评论之前的伪代码:-))

答案 1 :(得分:0)

如果要做的只是丢弃文件的第一行,只需调用ReadLine()并在进一步处理之前丢弃结果:

// Discard the header row
sr.ReadLine()

// Do further processing
while ((txtline = sr.ReadLine()) != null)
{
}

请注意,一行不一定表示CSV中的一行。使用库来读取CSV。

答案 2 :(得分:0)

continue关键字将跳转到循环的下一次迭代。

while ((txtline = sr.ReadLine()) != null)
{
   if (txtline == heading) continue; //Ignore headers

   //do standard processing
}

此代码假设您在两个文件中都有相同的标头,如果没有,请将heading替换为您正在读取的文件的标头。

答案 3 :(得分:0)

虽然答案都是有效的,但每次都会使用库来解析CSV文件。

它不仅提供开箱即用的东西来跳过标题行,而且还会处理麻烦的东西,比如双引号内的逗号等。

CSVHelper是我的首选CSV解析库。

它还为您提供了非常好的语法,如上所述,引自上面的链接:

var csv = new CsvReader( textReader );
var records = csv.GetRecords<MyClass>();

更容易阅读;)