ไม่ได้เขียนนาน เขียนซะหน่อย
เราเข้าสู่ยุค scala banana กันแล้วนะครัช!!!
–
วิธี real excel ด้วย scala บน Play Framework
–
1 เพิ่ม library ดังนี้ ใน build.sbt
, "org.apache.poi" % "poi" % "3.14" , "org.apache.poi" % "poi-ooxml" % "3.14"
–
2. มี path ของ file excel ที่จะอ่าน แล้วดูดมาเป็น FileInputStream
(ในที่นี้อ่านจาก config ที่ชื่อ path.root)
private def openInputStream(filename: String): FileInputStream = { new FileInputStream(config.getString("path.root").get + "/" + filename) }
–
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 }
–
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 }
–
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._
–
เย้เย!!!
–