Reading Excel files in PySpark is straightforward once you understand the core methods and best practices. It lets you efficiently load tabular data for Spark SQL, DataFrames, or Pandas UDFs, making it ideal for large datasets. You’ll need PySpark installed (typically via `pip install pyspark`) and a `.xlsx` or `.xls` file. For best results, ensure your Excel file isn’t corrupted and contains no complex formatting—PySpark reads raw tabulated data only.

What You'll Need

  • A working PySpark environment (PySpark 3.0+ recommended). Install it via Python packages (e.g., `pyspark==3.5.0`) or the Spark standalone cluster.
  • A local or remote path to your Excel file (e.g., `file:///path/to/data.xlsx`).
  • Python 3.8+ with Spark installed in a virtual environment to avoid conflicts.
  • Optional: A dataset larger than your RAM if loading directly into Spark’s distributed memory (for small files, Pandas UDFs are often faster).

Step-by-Step

  1. Set up Spark session from pyspark.sql import SparkSession

    Launch a Spark session with minimal configuration: spark = SparkSession.builder \ .appName("ExcelReader") \ .getOrCreate() If using a cluster, add .master("yarn") or .master("local[*]") for local testing.

    Check Spark version: print(spark.version) (PySpark 3.0+ handles Excel natively via OpenJDK's libraries.

  2. Load the Excel file as a DataFrame

    Use .read with the option("header") flag to detect column names (for CSV-style Excel). For older versions (<3.0), specify inferSchema=True. Example:

    df = spark.read.option("header", "true") \ .option("inferSchema", "true") \ .csv("path/to/file.csv") # Works for .xlsx too!

    For PySpark ≥3.0, use .option("inferSchema", "false") to force schema parsing and avoid schema drift: df = spark.read.option("inferSchema", "false") \ .option("header", "true") \ .parquet("path/to/file") # Parquet is faster for large datasets Note: In 3.0+, PySpark automatically detects Excel columns if no options are set.

  3. Specify file path

    Replace "path/to/data.xlsx" with your file. For remote paths, use HDFS (e.g., hdfs://namenode:8020/path) or S3 (for AWS: s3a://bucket/path). Example with HDFS: df = spark.read.format("com.databricks.spark.xlsx") \ .option("useHeader", "true") \ .load("hdfs://path/to/file.xlsx")

    For local files, use file:///... or just the path (e.g., ./data.xlsx).

  4. Handle complex scenarios
    1. Sheets vs. single sheet

      By default, PySpark loads the first sheet. To load multiple sheets: df = spark.read.option("inferSchema", "false") \ .format("com.databricks.spark.xlsx") \ .load("file.xlsx", {"sheetName": "Sheet1,Sheet2"}) Note: Avoid commas in sheet names; use quotes or hyphens.

    2. Hidden/protected data

      PySpark skips hidden sheets by default. Force inclusion: df = spark.read.option("inferSchema", "false") \ .format("com.databricks.spark.xlsx") \ .load("file.xlsx", {"sheetName": "allSheets"})

      For encrypted files, add .option("password", "your_pass") (use cautiously—passwords are logged in logs).

    3. Data types

      Use .option("dataTypeMapping", "true") to auto-map Excel types (e.g., dates strings to timestamp). For custom types, write a UDF: from pyspark.sql.functions import udf from pyspark.sql.types import StringType date_udf = udf(lambda x: x.split('-')[0], StringType()) df = df.withColumn("year", date_udf("date_column"))

Common Mistakes

  • Schema mismatch

    Excel may have 10 columns but Spark reads only 5. Fix by:

    1. Adding missing columns as empty strings (df.withColumn("new_col", lit(""))).
    2. Specifying schema manually: from pyspark.sql.types import StructType, StructField, StringType schema = StructType([StructField("col1", StringType()), ...]) df = spark.read.schema(schema).csv("file.csv")

  • Performance issues

    Large Excel files (>1GB) cause memory spikes. Solutions:

    • Use .option("columnMapping", "col1=name1,col2=name2") to minimize data transfer.
    • Load only specific sheets/tables.
    • For very large files, convert to Parquet first: df.write.parquet("output.parquet", mode="overwrite")

  • Corrupted files

    Check for:

    1. Excel file errors (open in Excel first).
    2. Incorrect path (use absolute paths).
    3. Missing dependencies (PySpark may fail silently).

    Test with a minimal file to isolate the issue.

Tips

  • Optimize for small files

    For <100MB files, use Pandas UDFs for speed: from pyspark.sql.functions import pandas_udf @pandas_udf("int") def read_excel(pandas_df): return pandas_df["col"].astype(int) df = df.withColumn("custom_col", read_excel(F.col("original_col")))

    Only use this if Spark’s native reader is too slow.

  • Validate data before loading

    Add a check for nulls or empty rows: df = df.filter(F.col("column").isNotNull())

    Or use .na.drop() after loading.

  • Use Spark SQL for transformations

    After loading, rewrite to SQL for complex aggregations: df.createOrReplaceTempView("data") df_spark_sql = spark.sql("SELECT col1, SUM(col2) FROM data GROUP BY col1")

    This avoids DataFrame API overhead.

  • Monitor memory usage

    Add .option("spark.executor.memory", "4g") if Spark dies during loading. Use spark.sparkContext.statusTracker to check. For 100GB files, consider spark.executor.memoryOverhead settings.

Troubleshooting

If PySpark fails to read the Excel file, follow this order:

  1. Check the path

    Verify the file exists and is accessible. On Windows, use raw strings for paths: r"C:\path\to\file.xlsx"

    On Linux/macOS, forward slashes or double slashes work: /home/user/data/file.xlsx

  2. Test with a minimal file

    Create a 1-sheet Excel file with 3 columns (A1:B1:C1) and df = spark.read.csv("minimal_file.xlsx", header=True). If it works, the issue is in your original file.

  3. Enable logging

    Add these options to debug: spark.conf.set("spark.logConf", "true") # Show configuration logs spark.conf.set("spark.executor.extraJavaOptions", "-Dlog4j.configuration=file:/path/to/log4j.properties")

    Look for "com.databricks" or "openxlsx" warnings in Spark logs.

  4. Downgrade PySpark (if <3.0)

    Old versions (<2.4) lack Excel support. Use pyspark==2.4.5 for basic .xls/.xlsx:

    df = spark.read.format("com.sun.star.script") \ .option("header", "true") \ .csv("file.xlsx")

    Note: This is a workaround; prefer PySpark 3.0+. Check pyspark.sql.types for available formats.

  5. Check Spark dependencies

    Ensure your environment has:

    • OpenJDK 8+ (PySpark 3.0+ requires JRE 8).
    • For HDFS/S3, install Abfs library: pip install abfs-storage-spark

    Run pip list | grep spark to verify all packages.

  6. Use a different reader

    If PySpark fails, try pandas.read_excel for small files: import pandas as pd df_pandas = pd.read_excel("file.xlsx") spark_df = spark.createDataFrame(df_pandas)

    This avoids Spark’s native limitations but doesn’t scale.

  7. Restart the Spark session

    Sometimes a stale session causes issues. Delete and recreate: from pyspark import SparkContext sc.stop() spark = SparkSession.builder.getOrCreate()

Frequently Asked Questions

How do I read a .xls (Excel 97-2003) file?

Use the com.sun.star.script format (PySpark <2.4) or convert to .xlsx first. For older Spark versions, add: df = spark.read.format("com.sun.star.script") \ .option("header", "true") \ .load("file.xls") But avoid this—modern Excel files (.xlsx) are required for PySpark 3.0+.

Why is my DataFrame empty after reading?

Check these first:

  1. Is the path correct? Use absolute paths.
  2. Is the file open in Excel? Save as .xlsx first.
  3. Does the file have a header row? Add header="true".
  4. Are there hidden sheets? Force load all: .option("sheetName", "allSheets")

Debug with df.count() (returns 0 if empty).

Can I read Excel files from S3 without AWS credentials?

No. Use a temporary credentials file or IAM role. Example: spark.conf.set("fs.s3a.access.key", "your_key") spark.conf.set("fs.s3a.secret.key", "your_secret") df = spark.read.option("header", "true").csv("s3a://bucket/path.xlsx")

For production, use AWS credentials stored securely.

What’s the fastest way to read a 1GB Excel file?

Use Parquet output after reading: df.write.parquet("output.parquet", mode="overwrite") df = spark.read.parquet("output.parquet")

Or parse only specific columns: df = spark.read.option("columnMapping", "col1=colA,col2=colB") \ .csv("file.xlsx")

For UDFs, limit rows with .limit() in a batch process.

How do I handle Excel’s row limits (e.g., 65,536 rows)?

Excel files exceed 65K rows by default. Solutions:

  1. Split the file: Save as 3 separate Excel files and merge in Spark: dfs = [spark.read.csv(f"part_{i}.xlsx") for i in range(3)] merged_df = dfs[0].unionAll(dfs[1]).unionAll(dfs[2])
  2. Use a UDF to read in chunks: Process Excel files line-by-line in a loop.
  3. Convert to CSV first: Excel’s CSV export supports unlimited rows.

For large datasets, consider spark.sql.dynamicAllocation.enabled=true to manage executors dynamically.

Why does my DataFrame have NaN values when reading dates?

Excel dates in text format become NaT (not a timestamp). Fix with:

  1. Convert to timestamp: df = df.withColumn("date_col", F.to_date("date_text_col", "yyyy-MM-dd"))
  2. Or map dates: df = df.withColumn("year", F.year(F.to_date("date_text_col")))

If dates are strings like "01/01/2023", specify the format: .to_date("date_text_col", "MM/dd/yyyy")