2017-06-02 170 views
0

我想使用poi SXSSF讀取excel文件。由於某種原因,即使表單中有行,sheet.rowIterator也會返回空的迭代器。這裏是我的代碼在scala中使用apache poi讀取excel文件

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()) 
    } 
} 

不知道我在做什麼錯。

+1

https://stackoverflow.com/questions/10053421/how-to-use-poi-sxssf-to-read-a-large-spreadsheet –

回答

0

這裏是一個簡單的例子,讀取我嘗試過的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("") 
    } 

希望這有助於!

+0

@Satish做到了這一點? –

相關問題