从CSV文件中跳过行

时间:2019-11-26 08:38:22

标签: .net-core csvhelper

我正在使用CSVHelper(https://github.com/JoshClose/CsvHelper/blob/master/src/CsvHelper/Configuration/IReaderConfiguration.cs)来读取csv文件,并且我想从文件开头跳过一定数量的行。是否可以使用“ ShouldSkipRecord”来实现这一目标?

2 个答案:

答案 0 :(得分:0)

如果您知道所有行都以某个字符开头,则可以使用ShouldSkipRecord

public class Program
{
    public static void Main(string[] args)
    {

        using (MemoryStream stream = new MemoryStream())
        using (StreamWriter writer = new StreamWriter(stream))
        using (StreamReader reader = new StreamReader(stream))
        using (CsvReader csv = new CsvReader(reader))
        {
            writer.WriteLine("# Something here.");
            writer.WriteLine("# Another line we don't need.");
            writer.WriteLine("Id,Name");
            writer.WriteLine("1,George");
            writer.Flush();
            stream.Position = 0;

            csv.Configuration.ShouldSkipRecord = row => row[0].StartsWith("#");                

            var records = csv.GetRecords<Foo>().ToList();
        }
    }
}

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

如果您知道要跳过前2行,则可以使用。

public class Program
{
    public static void Main(string[] args)
    {

        using (MemoryStream stream = new MemoryStream())
        using (StreamWriter writer = new StreamWriter(stream))
        using (StreamReader reader = new StreamReader(stream))
        using (CsvReader csv = new CsvReader(reader))
        {
            writer.WriteLine("Something here.");
            writer.WriteLine("Another line we don't need.");
            writer.WriteLine("Id,Name");
            writer.WriteLine("1,George");
            writer.Flush();
            stream.Position = 0;

            for (int i = 0; i < 2; i++)
            {
                csv.Read();
            }

            var records = csv.GetRecords<Foo>().ToList();
        }
    }
}

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

答案 1 :(得分:0)

以下是对我有用的:

var config = new CsvConfiguration(CultureInfo.InvariantCulture)
                    {
                        ShouldSkipRecord = (row) =>
                        {
                            //your logic for skipping records goes here

                           return (string.IsNullOrEmpty(row.Record[7]);
                        }
                    };
using (var reader = new StreamReader("CsvFilePath"))
using (var csv = new CsvReader(reader, config))
        {
             lst = csv.GetRecords<Foo>().ToList();
        }