2017-01-16 89 views
1

我正尝试使用自定义DSL在Apache POI DSL加载和读取Excel文件。为excel文件打印单元格值

我想提供Excel支持火花和我使用Apache POI的目的。我在Scala中找到了上面的DSL存储库。我试图找到一种方式来读取单元格并使用Scala来打印它们。

object XlsLoader{ 
    def f1(): Unit ={ 
     val path = "/Users/shashi/data311.xlsx" 
     val res = Workbook(path) 
     val res1 = res.getOrElse(null) 
     println(res1) 

     println("one") 

     val q = res1.map { 
      x => 
       println("hello") 
       println(x) 
       println("sheetmap -- "+x.sheetMap) 
       println("flatten -- "+x.sheetMap.toList) 
       println("keys -- "+x.sheetMap.keys.toList) 

       println("1he") 
       x.sheetMap.keys.toList.foreach(n => println(n)) 
       println("2he") 

       println("toString -- "+x.toString()) 
     } 

     println("two") 
     println(q) 
    } 
} 

这是输出。

[email protected] 
one 
two 
[email protected] 

我想找到工作表的内部结构并打印出来。我该怎么做 ?

这是供您参考的excel文件。

c1 c2 
1 100 
2 200 
3 300 
4 400 
5 500 
+0

你在答案中需要一些更具体的内容,或者你可以接受吗? – tkachuko

+0

我接受答案,因信誉而不能满意。现在我需要把这个excel转换成数据框,但是这个超出了这个问题的范围,如果有的话,建议任何有用的链接。 –

+0

如果您接受答案,您能否将其标记为正确的(带绿色勾号)? – tkachuko

回答

1

所以我用以下依赖性:

"info.folone" %% "poi-scala" % "0.18" 

现在在代码中唯一缺少的是调用.run.unsafePerformIO(它以上的安全替代)的。

此外,我创建了一个小样本可以解释它一步一步,并提供给.xls文件安慰的总体结构,希望这将是有益的:

import java.io.InputStream 

import info.folone.scala.poi._ 

import scalaz.{-\/, \/-} 

object ReadExcelFile { 

    def main(args: Array[String]): Unit = { 
    val readResult = Workbook(xlsFile) 
     .map(workbook => workbook.sheets) 
     .run 
     .unsafePerformIO() 
    readResult match { 
     case -\/(exception) => throw new RuntimeException("Could not read file", exception) 
     case \/-(sheets) => sheets.foreach(printSheet) 
    } 
    } 

    def printSheet(sheet: Sheet): Unit = { 
    println(s"------------ ${sheet.name} ------------\n") 
    sheet.rows.foreach(printRow) 
    } 

    def printRow(row: Row): Unit = println(row.cells.toList.sortBy(_.index).mkString(", ") + "\n") 

    def xlsFile: InputStream = ReadExcelFile.getClass.getResourceAsStream("/test.xls") 
} 

输出打算是这样的:

------------ Sample-spreadsheet-file ------------ 

FormulaCell(0, "=A1+1"), StringCell(1, "1.7 Cubic Foot Compact "Cube" Office Refrigerators"), StringCell(2, "Barry French"), NumericCell(3, 293.0), NumericCell(4, 457.81), NumericCell(5, 208.16), NumericCell(6, 68.02), StringCell(7, "Nunavut"), StringCell(8, "Appliances"), NumericCell(9, 0.58) 

正如你可以看到它打印的细胞类型,内容和工作表名称。

希望它有帮助!