CSV记录中的字符串列表?

时间:2014-08-01 18:11:55

标签: csv f# export-to-csv

如何在不将列表截断的情况下将记录中的字符串列表写入CSV?

CSV Writer:

let toSepFile sep header (fileName:string) (s:'record seq)=

    let schemaType=typeof<'record>
    let fields = Reflection.FSharpType.GetRecordFields(schemaType) 

    let toStr fields = 
        fields
        |> Seq.fold(fun res field-> res+field+sep) ""

    use w = new System.IO.StreamWriter(fileName)

    if header then 
        let header_str= fields
                    |> Seq.map(fun field -> field.Name)
                    |> toStr

        w.WriteLine(header_str)

    let elemToStr (elem:'record) = 
        //for each field get value 
        fields
        |> Seq.map(fun field -> string (FSharpValue.GetRecordField(elem,field)))
        |> toStr

    s
    |>Seq.map(elemToStr)
    |>Seq.iter(fun elem -> w.WriteLine(elem))

测试数据(Deedle测试集):

let peopleRecds = 
 [ { Name = "Joe"; Age = 51; Countries = [ "UK"; "US"; "UK"] }
 { Name = "Tomas"; Age = 28; Countries = [ "CZ"; "UK"; "US"; "CZ" ] }
 { Name = "Suzanne"; Age = 15; Countries = [ "US" ] } ]

当前CSV输出:

Name    Age Countries   
"Joe    51  [CZ; UK; US; ... ]  "
"Tomas  28  [CZ; UK; US; ... ]  "
"Suzanne    15  [US]    "

因此可以从CSV输出中看到完整的字符串列表,而不是&#34; ...&#34;?

编辑:所需的输出:

    Name    Age Countries   
    "Joe      51    [CZ; UK; US]    "
    "Tomas    28    [CZ; UK; US; CZ]    "
    "Suzanne  15    [US]    "

1 个答案:

答案 0 :(得分:0)

您遇到的问题是,对于ListToString()方法会截断输出。解决方法是不使用ToString(),而是使用sprint "%A" *list here*