Skip to content

Instantly share code, notes, and snippets.

@jramb
Created June 13, 2011 14:24
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jramb/1022853 to your computer and use it in GitHub Desktop.
Save jramb/1022853 to your computer and use it in GitHub Desktop.
Creating and updating Excel files with Clojure/poi.apache.org
((ns excel.core
(:import [org.apache.poi.hssf.usermodel HSSFWorkbook HSSFSheet HSSFRow
HSSFRichTextString HSSFFont HSSFDataFormat
HSSFCellStyle HSSFCell])
(:import [java.io FileOutputStream FileInputStream IOException])
#_(:import [org.apache.poi.ss.util CellRangeAdrress]))
(defn make-excel [file-name]
(let [wb (HSSFWorkbook.)
s (.createSheet wb)]
(.setSheetName wb 0 "HSSF Test")
(dorun (for [idx (range 100)]
(let [row (.createRow s idx)]
(dorun (for [col (range 100)]
(let [c (.createCell row col)]
(.setCellValue c (double (* idx col)))))))))
(with-open [out (FileOutputStream. file-name)]
(.write wb out))
))
(defn update-excel [file-name]
(let [wb (HSSFWorkbook. (FileInputStream. file-name))
s (.getSheetAt wb 0)
last-row (.getLastRowNum s)
row (.createRow s (inc last-row)) ; .getRow
cell (.createCell row 0) ; .getCell
date-style (doto (.createCellStyle wb)
(.setDataFormat (-> wb .getCreationHelper .createDataFormat (.getFormat "yyyy-m-d h:mm"))))]
;Java: date-style.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("yyyy-m-d h:mm"));
(doto cell
(.setCellStyle date-style)
(.setCellValue (java.util.Date.)))
(.setCellValue (.createCell row 1) "I was here")
(with-open [out (FileOutputStream. file-name)]
(.write wb out))))
(defn -main []
(make-excel "testing.xls")
(update-excel "update.xls")
)
(defproject excel "1.0.0-SNAPSHOT"
:description "FIXME: write description"
:dependencies [[org.clojure/clojure "1.2.1"]]
; you need poi-3.7-20101029.jar (1.5 MB) from the Apache poi project
:main excel.core)
@vikbehal
Copy link

vikbehal commented Nov 2, 2011

How do we read existing excel sheet!

@jramb
Copy link
Author

jramb commented Nov 2, 2011

(HSSFWorkbook. (FileInputStream. file-name))

is the key line for reading an existing file

@theronic
Copy link

When trying to load an Excel 5.0/7.0 sheet from an industrial pH sensor, I'm getting the following exception when calling (HSSFWorkbook. (FileInputStream. (str "/path/to/file.xls"))):

CompilerException org.apache.poi.hssf.OldExcelFormatException: The supplied spreadsheet seems to
be Excel 5.0/7.0 (BIFF5) format. POI only supports BIFF8 format (from Excel versions 97/2000/XP/2003), compiling`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment