Skip to content

Instantly share code, notes, and snippets.

@tjg
Created March 15, 2017 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjg/5c01b2bc1f6c2043ab2dcd2ec39d2328 to your computer and use it in GitHub Desktop.
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
(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