Created
March 15, 2017 20:39
-
-
Save tjg/5c01b2bc1f6c2043ab2dcd2ec39d2328 to your computer and use it in GitHub Desktop.
Little hack I use to extend Excel tables to the end of the data when using the excellent tomfaulhaber/excel-templates
This file contains hidden or 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
(defn extend-table-to-end! [table worksheet] | |
(try | |
(let [start (.getStartCellReference table) | |
end (.getEndCellReference table) | |
last-row-num (.getPhysicalNumberOfRows worksheet) | |
;; Excel doesn't like zero-sized tables. | |
last-row-num (if (= last-row-num (.getRow start)) | |
(inc last-row-num) | |
last-row-num) | |
new-range (-> (CellRangeAddress. (.getRow start) last-row-num | |
(.getCol start) (.getCol end)) | |
.formatAsString)] | |
(-> table .getCTTable (.setRef new-range))) | |
(catch Exception e | |
(println (format | |
"Ignoring error '%s' when extending table in worksheet: '%s'" | |
(.getMessage e) (excel/sheet-name worksheet)))))) | |
(defn extend-all-tables-to-end! [path] | |
(let [workbook (->> path | |
excel/load-workbook) | |
tables (->> workbook | |
excel/sheet-seq | |
(mapcat (fn [worksheet] | |
(->> worksheet | |
.getTables | |
(map (fn [table] | |
{:table table | |
:worksheet worksheet}))))) | |
doall)] | |
(doseq [{:keys [table worksheet]} tables] | |
(extend-table-to-end! table worksheet)) | |
(with-open [out (java.io.FileOutputStream. path)] | |
(do (.write workbook out) | |
(.flush out))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment