【问题标题】:Reading excel file using apache poi in scala在scala中使用apache poi读取excel文件
【发布时间】:2017-06-02 16:00:43
【问题描述】:

我正在尝试使用 poi SXSSF 读取 excel 文件。出于某种原因,即使工作表中有行, sheet.rowIterator 也会返回空迭代器。这是我的代码

import java.io.File
import org.apache.poi.xssf.streaming.SXSSFWorkbook
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import scala.collection.JavaConverters._

class ExcelReader {
    final val fileName = "c:\\temp\\data-200.xlsx"
    def read(): Iterator[Contact] = {
        val file = new File(fileName)
        val workBook = new SXSSFWorkbook(new XSSFWorkbook(file),100)
        val sheet = workBook.getSheetAt(0) //this works gets sheet name
        Console.println(s"Sheet Name: ${sheet.getSheetName()}")
        val rowItr = sheet.rowIterator().asScala // this is empty iterator
        for (e <- rowItr) yield Contact(e.getCell(0).getStringCellValue(), 
               e.getCell(1).getStringCellValue(), 
               e.getCell(2).getStringCellValue(), 
               e.getCell(3).getStringCellValue(),
               e.getCell(4).getStringCellValue())
    }
}

不知道我做错了什么。

【问题讨论】:

标签: excel scala apache-poi


【解决方案1】:

这是一个我尝试过的读取excel文件的简单示例。

val myFile = new File("/home/sakoirala/Downloads/eu-historical-price-series_en.xls")

  val fis = new FileInputStream(myFile)

  val myWorkbook = new HSSFWorkbook(fis)

  val mySheet = myWorkbook.getSheetAt(0)

  val rowIterator = mySheet.iterator()

  while(rowIterator.hasNext){

    val row = rowIterator.next()

      val cellIterator = row.cellIterator()

      while(cellIterator.hasNext) {
        val cell = cellIterator.next()
          cell.getCellType match {
            case Cell.CELL_TYPE_STRING => {
              print(cell.getStringCellValue + "\t")
            }
            case Cell.CELL_TYPE_NUMERIC => {
              print(cell.getNumericCellValue + "\t")
            }
            case Cell.CELL_TYPE_BOOLEAN => {
              print(cell.getBooleanCellValue + "\t")
            }
            case Cell.CELL_TYPE_BLANK => {
              print("null" + "\t")
            }
            case _ => throw new RuntimeException(" this error occured when reading ")
            //        case Cell.CELL_TYPE_FORMULA => {print(cell.getF + "\t")}
          }
      }
      println("")
  }

希望这会有所帮助!

【讨论】:

  • @Satish 这有帮助吗?