我如何克服文件未找到异常

时间:2019-06-04 16:59:19

标签: apache-spark dataframe

我正试图读取一个目录下的多个excel文件,但遇到java.io.FileNotFoundException错误:文件路径/ **不存在

          object example {
                 def main(args: Array[String]): Unit = {
           val spark = SparkSession.builder().appName("Excel to 
                     DataFrame").master("local[2]").getOrCreate()

val path = "C:\\excel\\files"
val df = spark.read.format("com.crealytics.spark.excel")
 .option("location", "true")
 .option("useHeader", "true")
 .option("treatEmptyValuesAsNulls", "true")
 .option("inferSchema","true")
 .option("addColorColumns", "true")
 .option("timestampFormat", "MM-dd-yyyy HH:mm:ss")
 .load("path")

1 个答案:

答案 0 :(得分:1)

尝试一下:

def readExcel(file: String): DataFrame = sqlContext.read
    .format("com.crealytics.spark.excel")
    .option("location", file)
    .option("useHeader", "true")
    .option("treatEmptyValuesAsNulls", "true")
    .option("inferSchema", "true")
    .option("addColorColumns", "False")
    .load()

val data = readExcel("path to your excel file")

data.show(false)

如果您想阅读特定的图纸:

.option("sheetName", "Sheet2")

编辑:要将多个Excel文件读取到一个数据框中。 (前提是excel文件中的列是一致的) 为此,我使用了spark-excel软件包。可以将其添加到build.sbt文件中,如下所示:

libraryDependencies += "com.crealytics" %% "spark-excel" % "0.8.2"

代码如下:

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.{SparkSession, DataFrame}
import java.io.File

val conf = new SparkConf().setAppName("Excel to DataFrame").setMaster("local[*]")
val sc = new SparkContext(conf)
sc.setLogLevel("WARN")

val spark = SparkSession.builder().getOrCreate()

// Function to read xlsx file using spark-excel. 
// This code format with "trailing dots" can be sent to Scala Console as a block.
def readExcel(file: String): DataFrame = spark.read.
  format("com.crealytics.spark.excel").
  option("location", file).
  option("useHeader", "true").
  option("treatEmptyValuesAsNulls", "true").
  option("inferSchema", "true").
  option("addColorColumns", "False").
  load()

val dir = new File("path to your excel file")
val excelFiles = dir.listFiles.sorted.map(f => f.toString)  // Array[String]

val dfs = excelFiles.map(f => readExcel(f))  // Array[DataFrame]
val ppdf = dfs.reduce(_.union(_))  // DataFrame 

ppdf.count()
ppdf.show(5)

希望这会有所帮助。祝你好运。