读取CSV时跳过标头

本文关键字:CSV 读取 | 更新日期: 2023-09-27 17:59:31

我希望在读写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循环中这样做,但我不知道如何跳过一行。

读取CSV时跳过标头

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

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

请注意,一行并不一定意味着CSV中的一行。使用库读取CSV。

只需计算行数即可;忽略它:

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

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

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

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

这段代码假设您在两个文件中都有相同的头,如果没有,请用正在读取的文件的头替换heading

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

它不仅提供了开箱即用的东西来跳过标题行,而且还将处理诸如双引号内的逗号等令人讨厌的事情。

CSVHelper是我的CSV解析库。

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

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

阅读起来容易多了;)