Scala อ่าน excel (อีกรอบ)

ไม่ได้เขียนนาน เขียนซะหน่อย

เราเข้าสู่ยุค scala banana กันแล้วนะครัช!!!

วิธี real excel ด้วย scala บน Play Framework

1 เพิ่ม library ดังนี้ ใน build.sbt

, "org.apache.poi" % "poi" % "3.14"
, "org.apache.poi" % "poi-ooxml" % "3.14"

Screen Shot 2016-08-20 at 10.40.35 AM.png

2. มี path ของ file excel ที่จะอ่าน แล้วดูดมาเป็น FileInputStream

(ในที่นี้อ่านจาก config ที่ชื่อ path.root)

private def openInputStream(filename: String): FileInputStream = {
  new FileInputStream(config.getString("path.root").get + "/" + filename)
}

Screen Shot 2016-08-20 at 10.43.11 AM.png

3. วนลูปอ่านไปทีละบรรทัด

ตรงนี้ใช้ method ตาม lib ตาม apache poi ของ java ได้เลย

def parse(file: String): List[List[String]] = closer(openInputStream(file)) { stream =>
  val workbook = new XSSFWorkbook(stream)
  val sheet: Sheet = workbook.getSheetAt(0)

  sheet.iterator.map(row =>
    row.iterator.map(cell =>
      read(cell)
    ).toList
  ).toList
}

Screen Shot 2016-08-20 at 10.48.29 AM

4. อ่าน cell นั้นๆ ด้วย method นี้

private def read(cell: Cell): String = {
  val result = cell.getCellType match {
    case Cell.CELL_TYPE_STRING => cell.getRichStringCellValue
    case Cell.CELL_TYPE_NUMERIC => cell.getNumericCellValue
    case Cell.CELL_TYPE_BOOLEAN => cell.getBooleanCellValue
    case Cell.CELL_TYPE_FORMULA => cell.getCellFormula
  }

  result.toString
}

Screen Shot 2016-08-20 at 10.51.56 AM.png

5. เช็ค import ตามด้านล่าง เป็นอันจบ

import java.io.FileInputStream
import javax.inject.{Inject, Singleton}

import org.apache.poi.ss.usermodel.{Cell, Sheet}
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import play.api.Configuration
import utils.Closer

import scala.collection.JavaConversions._

Screen Shot 2016-08-20 at 10.53.00 AM

เย้เย!!!

About champillon

Enterprise Opensource Implementer
This entry was posted in Scala and tagged . Bookmark the permalink.

Leave a comment