-1

我必须读取 xlsx 文件的整个目录,并且需要使用 Scala 使用 Apache Spark 加载所有目录。

实际上我正在使用这个依赖项: "com.crealytics" %% "spark-excel" % "0.12.3",我不知道如何加载所有内容。

4

1 回答 1

1

似乎没有通过选项方法将快捷选项放入路径中。因此,我创建了如下解决方法(假设每个 excel 文件具有相同的列数)。创建了一个方法来获取源目录中每个文件的所有路径,并在这些文件路径上运行一个循环,创建新的数据框并附加到前一个。

import java.io.File
import org.apache.spark.sql.Row
import org.apache.spark.sql.types._

def getListOfFiles(dir : String) : List[File] = {
  val d = new File(dir)
  if (d.exists && d.isDirectory){
    d.listFiles().filter(_.isFile).toList
  } else {
      List[File]()
  }
}

val path = " \\directory path"

// shows list of files with fully qualified paths
println(getListOfFiles(path))

val schema = StructType(
    StructField("id", IntegerType, true) ::
    StructField("name", StringType, false) ::
    StructField("age", IntegerType, false) :: Nil)


// Created Empty dataframe with as many columns as in each excel
var data = spark.createDataFrame(spark.sparkContext.emptyRDD[Row], schema)
for(filePath <- getListOfFiles(path)){
  var tempDF = spark.read.format("com.crealytics.spark.excel")
    .option("location", s"$filePath")
    .option("useHeader", "true")
    .option("treatEmptyValuesAsNulls", "true")
    .option("inferSchema", "true")
    .option("addColorColumns", "False")
    .load()
  data = data.union(tempDF)
}

data.show()
于 2019-10-19T19:06:31.433 回答