打印excel文件的单元格值

打印excel文件的单元格值,excel,scala,apache-poi,Excel,Scala,Apache Poi,我正在尝试使用自定义DSL加载和读取Excel文件 我想为spark提供Excel支持,并使用ApachePOI。我在Scala中找到了上述DSL存储库。我试图找到一种方法来读取单元格并使用Scala打印它们 object XlsLoader{ def f1(): Unit ={ val path = "/Users/shashi/data311.xlsx" val res = Workbook(path) val res1 = res.g

我正在尝试使用自定义DSL加载和读取Excel文件

我想为spark提供Excel支持,并使用ApachePOI。我在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)
    }
}
这是输出

scalaz.effect.IO$$anon$7@1a8e246b
one
two
scalaz.effect.IO$$anon$7@34ccc2af
我想找到这张纸的内部结构并打印出来。我该怎么做

这是供您参考的excel文件

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

因此,我使用了以下依赖项:

"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)
如您所见,打印单元格类型、内容和工作表名称。


希望有帮助

你需要答案中的更多细节吗?或者你可以接受它?我接受答案,因为声誉原因无法投票。现在我需要将此excel转换为数据框,但这超出了此问题的范围,如果有,请建议任何有用的链接。如果您接受答案,请将其标记为正确的(带绿色勾号)?