4
$\begingroup$

One question:

How can I export a DataSet to CSV and XLS ?

Dataset[{<|"A" -> 1, "B" -> 2|>, <|"A" -> 3, "B" -> 4|>, <|"A" -> 5, 
   "B" -> 6|>}]
$\endgroup$
7
  • 1
    $\begingroup$ Have a look at ExportString[dataset, "CSV"]. $\endgroup$ Commented Apr 10, 2018 at 15:27
  • $\begingroup$ @J.M. I got the following error: "Dataset of the given form could not be exported as format \ \"\!\(\"CSV\"\)\"" $\endgroup$
    – james
    Commented Apr 10, 2018 at 15:31
  • $\begingroup$ Interesting... I can export that particular example in 11.2. $\endgroup$ Commented Apr 10, 2018 at 15:32
  • $\begingroup$ @J.M. Maybe it is the version of Mathematica... I have 11.0 and I tried it with an even simple example (see question) and I still get the same error. $\endgroup$
    – james
    Commented Apr 10, 2018 at 15:33
  • $\begingroup$ You might see if this helps mathematica.stackexchange.com/questions/56737/… or you can search mathematica.stackexchange for Export Dataset and find a variety of questions and answers $\endgroup$
    – Bill
    Commented Apr 10, 2018 at 16:11

2 Answers 2

2
$\begingroup$

You can do the following:

entries = List @@@ Normal@dataset;
keys = dataset[1, Keys] // Normal

csvDataSet = PrependTo[entries, keys];

Export["text.csv", csvDataSet]
$\endgroup$
3
  • $\begingroup$ Nice ! Works ! :) $\endgroup$
    – james
    Commented Apr 10, 2018 at 18:29
  • $\begingroup$ I use a similar defined function frequently: assocToLists[assoc_] := Prepend[Values[Normal[assoc]], First[Keys[Normal[assoc]]]]; $\endgroup$
    – kickert
    Commented Oct 14, 2018 at 0:28
  • $\begingroup$ Any idea on how to answer the second part, export to XLS or XLSX? $\endgroup$ Commented Nov 14, 2023 at 16:12
8
$\begingroup$

According to documentation, Export can directly push out a dataset as an CSV. The below statements work fine.

ds = Dataset[{
   <|"a" -> 1, "b" -> 2, "Lunch" -> "Chicken", 
    "Luncheon Options" -> "", "Lunch Choices" -> ""|>,
   <|"a" -> 2, "b" -> 6, "Lunch" -> "", "Luncheon Options" -> "Beef", 
    "Lunch Choices" -> ""|>,
   <|"a" -> 3, "b" -> "7", "Lunch" -> "", "Luncheon Options" -> "", 
"Lunch Choices" -> "Lamb"|>
   }]
Export["Downloads/Lunch Options.csv", ds]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.