public
Last active

Convert numbers to Excel headers

  • Download Gist
col-str.clj
Clojure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
(let [chr (zipmap (range) "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
encode (fn [n acc]
(if (< n 26)
(cons n acc)
(recur (dec (quot n 26)) (cons (rem n 26) acc))))]
(defn col-str
"Convert numbers to Excel headers."
[n]
(apply str (map chr (encode n '())))))
 
;;(col-str 0)
;;=> "A"
;;(col-str 25)
;;=> "Z"
;;(col-str 26)
;;=> "AA"
;;(col-str 701)
;;=> "ZZ"
;;(col-str 702)
;;=> "AAA"
(def chrs (zipmap (range) "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))

(defn foo [n]
  (let [base 26 q (quot n base) r (rem n base) c (chrs r)]
    (if (zero? q) [c] (cons c (lazy-seq (foo (dec q)))))))

(defn str-num [n]
  (aply str (reverse (foo n))))

;; (map str-num [0 25 26 701 702])
;; => ("A" "Z" "AA" "ZZ" "AAA")

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.