【问题标题】:Print cell values for excel files打印 Excel 文件的单元格值
【发布时间】:2017-01-16 10:57:48
【问题描述】:

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

我想为 spark 和我使用 Apache POI 的目的提供 Excel 支持。我在 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

【问题讨论】:

  • 您需要在答案中提供更多细节还是可以接受?
  • 我接受答案,由于声誉问题无法投票。现在我需要将此excel转换为数据框,但这超出了这个问题的范围,如果你有任何有用的链接,请提出任何有用的链接。
  • 如果您接受答案,请您将其标记为正确答案(绿色勾号)?

标签: excel scala apache-poi


【解决方案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)

如您所见,它打印单元格类型、内容和工作表名称。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 2017-04-03
    相关资源
    最近更新 更多