I understand how to write to CSV using [clojure.data.csv] But I am at a loss as to write the CSV in this specific format.
The data I want to write to CSV is the result of a DB query using [clojure.java.jdbc] with the as-arrays? true modifier which returns a 2D array where [0][1] is the column names which need to become the headers in the CSV and then [x][y] will become the data to write to these headers so [1][0] will write the first returned row and column 0 to the CSV under the first heading.
(with-open [out-file (io/writer "out-file.csv")]
(csv/write-csv out-file
[["abc" "def"]
["ghi" "jkl"]]))
The above is an example of writing to CSV file, but I am unsure how to use the result of my query and write the values to CSV.
The data will look like this:
[[header1, header2, header3]
[val1, val2, val3]
[val1, val2, val3]]
The query looks like this:
(j/query db ["$SOME_QUERY"] as-arrays? true))
Can somebody help with this?
Edit: update this is what i have so far:
(defn write-query-to-csv [query db output-filename]
(log/info (str "Executing " query " on " db))
(let [results (j/query db ["$QUERY"]
:as-arrays? true)
header (->> results
first)
data (->> results)]
(with-open [out-file (io/writer output-filename)]
(csv/write-csv out-file
(reduce conj (conj [] header) data)))
(io/file output-filename)))
The header data is correct but I'm unsure how to populate the data variabale :/
s/FILL THIS IN/rest/?letyou pull the header sequence out, but don't strip it off of the data. So nowheadercontains a sequence of header labels, anddatacontains the header sequence plus the data sequences (one sequence for each row). Thereduceline adds the header sequence back on to the sequence of sequences--which now contains two header sequences. It looks as if theletonly needs to bindresult, and then you can passresultwith no modification as the second argument towrite-csv. That's it. Am I misunderstanding something?query, or the data you want to write to the file? That's why I can't post an answer--I'm not sure whatj/queryis returning. If you mean, by that comment, the data that you want to write to the file, then what isqueryreturning? Take a look at it, if you're not sure. (Add(println result), for example. If that's too much data, construct a different query, or usetaketo take only the first n rows.) My guess is thatresultis in exactly the format that you want.write-csvthen that may help others