Skip to content

Instantly share code, notes, and snippets.

@tjdett
Last active May 24, 2018 05:29
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tjdett/4735911 to your computer and use it in GitHub Desktop.
Save tjdett/4735911 to your computer and use it in GitHub Desktop.
Scala + Apache POI to read uploaded Excel doc
package com.example.app
import org.scalatra._
import servlet.{SizeConstraintExceededException, FileUploadSupport}
import scalate.ScalateSupport
import java.io.ByteArrayInputStream
import org.apache.poi.ss.usermodel.WorkbookFactory
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.DataFormatter
import org.apache.poi.ss.usermodel.DateUtil
import scala.collection.JavaConversions._
class MyScalatraServlet extends ScalatraServlet
with ScalateSupport
with FileUploadSupport {
get("/") {
<html>
<body>
<h1>Excel reading test</h1>
<p>Select a file to upload.</p>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<br/>
<button type="Submit">Upload</button>
</form>
</body>
</html>
}
post("/") {
fileParams.get("file") match {
case Some(file) =>
val wb = WorkbookFactory.create(new ByteArrayInputStream(file.get()))
val sheet = wb.getSheetAt(0)
def getCellString(cell: Cell) = {
cell.getCellType() match {
case Cell.CELL_TYPE_NUMERIC =>
(new DataFormatter()).formatCellValue(cell)
case Cell.CELL_TYPE_STRING =>
cell.getStringCellValue()
case Cell.CELL_TYPE_FORMULA =>
val evaluator = wb.getCreationHelper().createFormulaEvaluator()
(new DataFormatter()).formatCellValue(cell, evaluator)
case _ => " "
}
}
val text = sheet.rowIterator.map(row => {
row.cellIterator.map(getCellString).mkString("\t")
}).mkString("\n")
Ok(s"${file.name} has ${wb.getNumberOfSheets()} sheets.\n$text", Map(
"Content-Type" -> "text/plain"
))
case None =>
BadRequest("Hey! You forgot to attach a file.", Map(
"Content-Type" -> "text/plain"
))
}
}
notFound {
// remove content type in case it was set through an action
contentType = null
// Try to render a ScalateTemplate if no route matched
findTemplate(requestPath) map { path =>
contentType = "text/html"
layoutTemplate(path)
} orElse serveStaticResource() getOrElse resourceNotFound()
}
}
@revathikg
Copy link

revathikg commented Dec 8, 2016

I am getting error while importing "import servlet.{SizeConstraintExceededException, FileUploadSupport}".What kind of jar do I need to include?

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