PySpark cannot read .xlsx files natively, so you first convert the sheet to CSV or use the Spark Excel connector, then load it with spark.read. The quickest reliable route is to export the sheet to CSV and read it with spark.read.csv(); for multi-sheet or formatted workbooks, use the com.crealytics.spark.excel package. Both approaches are covered below.
What You'll Need
- A working Apache Spark installation (local or cluster) with PySpark installed, e.g.
pip install pyspark. - Java 8 or 11 available on the machine running Spark.
- An .xlsx or .xls file saved somewhere Spark can reach (local path, HDFS, or cloud storage).
- For the connector route: internet access to download the Maven package, or a pre-downloaded JAR.
- For the CSV route: Excel, LibreOffice, or a Python library such as pandas/openpyxl to do the conversion.
Step-by-Step
- Start a Spark session. In a Python script or notebook, create the session before reading anything:
from pyspark.sql import SparkSession spark = SparkSession.builder.appName("excel-read").getOrCreate() - Choose your route. Use the CSV route for a single sheet and simple data; use the connector route when you need to pick a sheet by name, handle headers, or read many workbooks in one job.
- CSV route — convert the workbook first. In Excel choose File > Save As and pick CSV UTF-8, or in Python:
This flattens one sheet at a time, so repeat for each sheet you need.import pandas as pd pd.read_excel("data.xlsx", sheet_name="Sheet1").to_csv("data.csv", index=False) - CSV route — read the CSV in Spark.
Setdf = spark.read.csv("data.csv", header=True, inferSchema=True) df.show()header=Trueso the first row becomes column names andinferSchema=Trueso numbers and dates are typed rather than left as strings. - Connector route — add the package. Launch Spark with the connector on the classpath, for example:
The version suffix (pyspark --packages com.crealytics:spark-excel_2.12:0.13.7_2.12) must match your Scala build; check your Spark version's Scala suffix before choosing a package version. - Connector route — read the sheet.
Thedf = spark.read.format("com.crealytics.spark.excel") \ .option("header", "true") \ .option("inferSchema", "true") \ .option("dataAddress", "'Sheet1'!A1") \ .load("data.xlsx") df.show()dataAddressoption names the sheet and starting cell; adjust it for your workbook. - Check the schema and row count. Run
df.printSchema()anddf.count()to confirm types and that no rows were silently dropped (for example, blank leading rows). - Clean up if needed. Rename columns with
withColumnRenamed, cast types withcast, and drop null-only rows withdropna(how="all")before analysis.
Common Mistakes
- Trying
spark.read.excel()directly. That method does not exist in stock PySpark; you must use the connector or convert to CSV. - Forgetting
header=True. Without it the header row becomes a data row and column names default to_c0,_c1, etc. - Leaving
inferSchemaoff. Every column arrives as a string and later numeric operations fail or misbehave. - Scala version mismatch. Using a connector built for a different Scala minor version throws a NoClassDefFound or linkage error at read time.
- Assuming all sheets load. Both routes read one sheet per call by default; loop over sheet names explicitly.
- Path confusion. A local Windows path like
C:\data\file.xlsxwill not resolve on a cluster; use a URI or a path visible to every executor.
Tips
- For repeated jobs, prefer CSV or Parquet as the stored format and keep Excel only as the source of truth; Parquet reads far faster in Spark.
- Use
spark.read.option("mode", "PERMISSIVE")on CSV reads when rows may have inconsistent column counts. - If the file is small, read it with pandas/openpyxl first, then create the Spark DataFrame with
spark.createDataFrame(pandas_df); this avoids connector setup entirely. - Keep the connector JAR version pinned in your job config so cluster upgrades do not silently change behaviour.
Troubleshooting
"Path does not exist" or FileNotFoundException. Confirm the path with dbutils.fs.ls (Databricks) or your filesystem tool, and remember executors need access to the same location as the driver.
ClassNotFoundException for the Excel format. The package was not loaded. Restart the session with --packages or add the JAR via spark.jars in the session config, then recreate the SparkSession.
All columns are strings. inferSchema was not set, or the sheet has mixed types in a column. Cast explicitly after reading.
Empty DataFrame. The dataAddress may point at the wrong sheet or cell, or the CSV has a blank first row. Inspect the raw file and adjust the address or use skipRows.
Garbled characters. The CSV was not saved as UTF-8; re-export with UTF-8 encoding and read with encoding="UTF-8".
Out-of-memory on large workbooks. Excel files are not splittable, so a single huge sheet lands on one partition. Convert to CSV/Parquet first, or increase driver memory.
Frequently Asked Questions
Can PySpark read .xlsx natively?
No. Stock PySpark has no Excel reader; you need the crealytics connector or a CSV conversion step.
Which is better, the connector or CSV?
CSV is simpler and dependency-free but loses formatting and needs one export per sheet. The connector handles multi-sheet workbooks in place but adds a version-matched JAR.
How do I read a specific sheet?
With the connector, set dataAddress to the sheet name and range. With CSV, export that sheet separately.
Can I read multiple Excel files at once?
Yes, pass a glob pattern such as data/*.xlsx to load(); all files must share the same schema.
Does this work on Databricks?
Yes. Install the connector as a cluster library, then use the same spark.read.format(...) call. Library install labels vary by workspace version.
Why are my dates wrong?
Excel stores dates as serial numbers. The connector usually converts them, but CSV exports may arrive as text; cast with to_date or to_timestamp after reading.