我们如何才能只获取特定列中包含数据的 CSV 标题?

问题描述 投票:0回答:1
A 栏 B 栏 C 栏 D 栏
abc -- bcd --
edf sdg -- rzh

例如:在第 1 行中,B 列和 D 列中没有数据。因此,对于第 1 行,标题输出应为 A 列、C 列。在第 2 行中,C 列中的数据不可用。因此,对于第 2 行,标题输出应为 A 列、C 列。标题输出应为 A 列、B 列、D 列。

string csvFilePath = "your_csv_file.csv";

        using (var reader = new StreamReader(csvFilePath))
        using (var csv = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture)))
        {
            // Read the CSV records into a dynamic list
            var records = csv.GetRecords<dynamic>().ToList();

            // Get the headers from the first record
            var headers = ((IDictionary<string, object>)records[0]).Keys.ToList();

            // Create a list to store headers with data
            var headersWithData = new List<string>();

            // Iterate through headers and check if any row in the column has data
            foreach (var header in headers)
            {
                if (records.Skip(1).Any(record => !string.IsNullOrWhiteSpace(record[header]?.ToString())))
                {
                    headersWithData.Add(header);
                }
            }

            // Print the filtered column headers with data
            Console.WriteLine("Column Headers with Data:");
            foreach (var header in headersWithData)
            {
                Console.WriteLine(header);
            }
        }
c# .net csv csvhelper
1个回答
0
投票

看起来就这么简单:

string[][] results =
    File
        .ReadAllLines(csvFilePath)
        .Select(x => x.ParseCsvLine())
        .Select(x => x.Where(y => !String.IsNullOrEmpty(y)).ToArray())
        .ToArray();

ParseCsvLine
将 CSV 中的
string
转换为
stringp[]

© www.soinside.com 2019 - 2024. All rights reserved.