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
- Set up Spark session
from pyspark.sql import SparkSessionLaunch 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. - Load the Excel file as a DataFrame
Use
.readwith theoption("header")flag to detect column names (for CSV-style Excel). For older versions (<3.0), specifyinferSchema=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 datasetsNote: In3.0+, PySpark automatically detects Excel columns if no options are set. - 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). - Handle complex scenarios
- 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. - 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). - 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"))
- Sheets vs. single sheet
Common Mistakes
- Schema mismatch
Excel may have 10 columns but Spark reads only 5. Fix by:
- Adding missing columns as empty strings (
df.withColumn("new_col", lit(""))). - Specifying schema manually:
from pyspark.sql.types import StructType, StructField, StringType schema = StructType([StructField("col1", StringType()), ...]) df = spark.read.schema(schema).csv("file.csv")
- Adding missing columns as empty strings (
- 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")
- Use
- Corrupted files
Check for:
- Excel file errors (open in Excel first).
- Incorrect path (use absolute paths).
- 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. Usespark.sparkContext.statusTrackerto check. For 100GB files, considerspark.executor.memoryOverheadsettings.
Troubleshooting
If PySpark fails to read the Excel file, follow this order:
- 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 - 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. - 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.
- Downgrade PySpark (if <3.0)
Old versions (<2.4) lack Excel support. Use
pyspark==2.4.5for 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.typesfor available formats. - 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 sparkto verify all packages. - Use a different reader
If PySpark fails, try
pandas.read_excelfor 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.
- 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:
- Is the path correct? Use absolute paths.
- Is the file open in Excel? Save as .xlsx first.
- Does the file have a header row? Add
header="true". - 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:
- 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]) - Use a UDF to read in chunks: Process Excel files line-by-line in a loop.
- 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:
- Convert to timestamp:
df = df.withColumn("date_col", F.to_date("date_text_col", "yyyy-MM-dd")) - 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")