创建 CSV 文件时中途添加字段

问题描述 投票:0回答:1

我需要从数据库表创建一个 CSV 文件,该文件在表的一列中保存 JSON 数据。表中的每一行都可以保存具有不同变量的 JSON。

我创建的 CSV 应该包含所有行中所有变量的字段。

示例:

数据库表中的第 1 行:

{"height":100,"weight":50}

数据库表中的第 2 行:

{"color":"red"}

数据库表中的第 3 行:

{"color":"blue","height":75}

要创建的 CSV:

height,weight,color
100,50,
,,red
,75,blue

由于表格可能包含数十万行,我想知道是否有一种方法可以在从表格中读取行并创建 CSV 的同时中途添加字段,而无需一次读取整个表格以获取所有字段,然后再次读取写入 CSV。

我过去曾使用 CSVHelper https://joshclose.github.io/CsvHelper/ 来处理 CSV 操作,但我没有看到适合我的场景的选项。

c# csv csvhelper
1个回答
0
投票

以下代码从包含 json 数据的字符串列表生成所需的输出。您可以从数据库读取数据来完成它:

public string GetCsv(string[] jsonValues) {

    var objectsAsDictionary = jsonValues.Select(_ =>
        JsonSerializer.Deserialize<Dictionary<string,object>>(_)).ToArray();

    using var textWriter =    new StringWriter();
    using var csv = new CsvWriter(textWriter, CultureInfo.InvariantCulture);
    var properties = objectsAsDictionary.SelectMany(_ => _.Keys)
        .Distinct().ToArray();

    foreach (var property in properties) {
        csv.WriteField(property);
    }
    csv.NextRecord();
    foreach (var item in objectsAsDictionary) {
        foreach (var property in properties) {
            object value = null;
            item.TryGetValue(property, out value);
            csv.WriteField(value);
        }
        csv.NextRecord();
    }
    return textWriter.ToString();
}

这是一个检查输出的测试:

var class1 = new Class1();
var rows = new[] {
    "{\"height\":100,\"weight\":50}",
    "{\"color\":\"red\"}",
    "{\"color\":\"blue\",\"height\":75}"
};

var result = class1.GetCsv(rows);
var expected = "height,weight,color" + Environment.NewLine +
"100,50," + Environment.NewLine +
",,red" + Environment.NewLine +
"75,,blue" + Environment.NewLine;
Assert.Equal(expected, result);
© www.soinside.com 2019 - 2024. All rights reserved.