the CSV type provider from FSharp.Data is primarily known and used to read CSV (as the name implies), but it is also quite capable of writing CSV.
All you have to do is determine the type, either by providing a sample .CSV file
let titanic2 = CsvProvider<"../data/Titanic.csv", Schema="Fare=float,PClass->Passenger Class">.GetSample()
or by directly defining the circuit
type MyCsvType = CsvProvider<Schema = "A (int), B (string), C (date option)", HasHeaders=false>
then you can create a recording object and fill it (in a safe way!)
// you can build the rows themselves let myCsv = new MyCsvType( [ MyCsvType.Row(1, "a", None) MyCsvType.Row(2, "B", Some DateTime.Now) ]) // or, for your scenario, you probably want to define a conversion function // from your record type to the CSV provider type let buildRowFromObject obj = MyCsvType.Row(obj.A, obj.B, obj.C) let buildTableFromObjects = (Seq.map buildRowFromObject) >> Seq.toList >> MyCsvType let myCsv = someSequenceOfObjects |> buildTableFromObjects
and finally just call
myCsv.SaveToString()
to get the result in CSV format.
source share