Created
June 26, 2017 09:17
-
-
Save HendrikLouw/2abfe0b3f6ced428bf1c5371edd404bb to your computer and use it in GitHub Desktop.
Export table to CSV with JS APIs and Clojuresript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; Extends Nodelist in order for us to just map through nodelists (array like js objects) | |
(extend-type js/NodeList | |
ISeqable | |
(-seq [array] (array-seq array 0))) | |
(defn download-csv [csv filename] | |
(let [csv-file (js/Blob. (clj->js [csv]) {:type "text/csv"}) | |
download-link (.createElement js/document "a")] | |
(aset download-link "download" filename) | |
(aset download-link "href" (.createObjectURL (aget js/window "URL") csv-file)) | |
(aset download-link "style.display" "none") | |
(.appendChild (aget js/document "body") download-link) | |
(.click download-link))) | |
(defn export-table-to-csv [table-id] | |
(let [row-selector (str "#" table-id " tr") | |
rows (.querySelectorAll js/document row-selector) | |
table (->> (map (fn [row] | |
(let [cols (.querySelectorAll row "th, td")] | |
(->> (map (fn [col] | |
(.-innerText col)) cols) | |
(clojure.string/join ",")))) rows) | |
(clojure.string/join "\n"))] | |
(download-csv table (str "table-export-" table-id ".csv")))) | |
; (export-table-to-csv "some-table-id") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment