To read an Excel file into PySpark in Microsoft Fabric, you must use a third-party library such as crealytics or pandas because Apache Spark does not have a native Excel reader. The most efficient method for large datasets is using the Spark-Excel connector, while the pandas approach is simpler for smaller files. This process allows you to transform static spreadsheet data into a distributed Spark DataFrame for large-scale analytics and machine learning within your Lakehouse environment.

What You'll Need

  • A Microsoft Fabric workspace with an active Lakehouse created.
  • An Excel file (.xlsx or .xls) uploaded to the "Files" section of your Lakehouse.
  • A Fabric Notebook attached to that Lakehouse.
  • Appropriate permissions to install libraries or modify the Spark environment.

Step-by-Step

  1. Upload the Excel File: Navigate to your Lakehouse in Microsoft Fabric. In the Explorer pane on the left, locate the "Files" folder. Right-click the folder or use the upload button to upload your Excel workbook from your local machine. Note the exact path of the file; it will typically follow the pattern Files/your_folder/your_file.xlsx.
  2. Install the Required Library: Since PySpark cannot read .xlsx files natively, you need a connector. The most common choice is the com.crealytics:spark-excel library. In your Fabric Notebook, you can install this by going to the "Environment" settings of your workspace or by using a pip install for pandas if you choose the pandas route. For the Spark-native approach, add the Maven coordinate com.crealytics:spark-excel_2.12:3.3.1_0.18 (ensure the version matches your Spark runtime) to your environment's public libraries.
  3. Define the File Path: In a notebook cell, define the path to your file. Because Fabric uses a distributed file system, you should use the ABFS (Azure Blob File System) path. You can find this by right-clicking the file in the Lakehouse explorer and selecting "Copy ABFS path".

    file_path = "abfss://workspace@onelake.dfs.fabric.microsoft.com/lakehouse/Files/data_source.xlsx"
  4. Configure the Read Options: You must specify how Spark should interpret the Excel file. Key options include dataAddress (to specify a specific sheet name or cell range), header (set to "true" if the first row contains column names), and inferSchema (set to "true" to let Spark guess the data types).
  5. Execute the Read Command: Use the spark.read format. If using the crealytics library, the code looks like this:

    df = spark.read.format("com.crealytics.spark.excel") \n .option("dataAddress", "'Sheet1'!A1") \n .option("header", "true") \n .option("inferSchema", "true") \n .load(file_path)
  6. Alternative Method (Pandas Bridge): If you are dealing with a small file and don't want to configure Maven libraries, use pandas to read the file and then convert it to a Spark DataFrame:

    import pandas as pd pdf = pd.read_excel(file_path) df = spark.createDataFrame(pdf)
    Note: The pandas method loads the entire file into the driver's memory, which can cause an Out of Memory (OOM) error if the file is too large.
  7. Verify the Data: Use df.show() or display(df) to ensure the columns and rows have been imported correctly. Check that dates are recognized as timestamps and numbers are not treated as strings.

Common Mistakes

One of the most frequent errors is attempting to use spark.read.csv() on an Excel file. While both are spreadsheets, they are fundamentally different formats; CSV is plain text, while XLSX is a zipped XML structure. This will result in a "Malformed record" or "Unable to parse" error.

Another common mistake is ignoring the sheet name. By default, some connectors only read the first sheet. If your data resides on a sheet named "Sales_2023", but you do not specify the dataAddress, you may end up with an empty DataFrame or data from the wrong tab.

Users often forget to handle the "Driver Memory" limit when using the pandas bridge. Because pd.read_excel runs on the Spark Driver node rather than across the worker nodes, a 500MB Excel file can easily expand to several gigabytes in RAM, crashing the notebook session.

Incorrectly specifying the ABFS path is also common. Using a local path like /lakehouse/default/Files/... might work in some contexts but often fails when the Spark job is distributed across the cluster. Always prefer the full ABFS URI for stability.

Tips

For maximum performance, convert your Excel files to Parquet or Delta format as soon as they are ingested. Excel is a row-based, non-compressed format that is slow for Spark to process. Once you have read the file into a DataFrame, use df.write.format("delta").save("Tables/my_table") to store it as a managed table in your Lakehouse.

If your Excel file has complex formatting, such as merged cells or multiple header rows, clean the file in Excel first. Spark expects a tabular structure. If you have three rows of titles before the actual column headers, use the dataAddress option to start reading from the specific row (e.g., 'Sheet1'!A4) where the headers actually begin.

When using inferSchema, be aware that Spark only reads a portion of the file to guess the types. If a column is mostly numbers but has a few strings at the bottom, Spark might cast the whole column as integers and turn the strings into nulls. To prevent this, manually define a schema using StructType and StructField.

If you are automating this process via a Pipeline, consider using a Dataflow Gen2. Dataflow Gen2 has a native Excel connector that provides a visual interface for cleaning and transforming the data before it ever hits your PySpark notebook, reducing the amount of boilerplate code you need to write.

Troubleshooting

If you encounter a ClassNotFoundException: com.crealytics.spark.excel, it means the Spark-Excel library is not installed on the cluster. Go to your Fabric Environment settings, check the "Libraries" section, and ensure the Maven coordinate is added and the environment is published. You must restart your notebook session for the new library to take effect.

If the notebook hangs or crashes with an OutOfMemoryError during a pandas read, switch to the com.crealytics Spark-native reader. If you must use pandas, try reading only the necessary columns using the usecols parameter in pd.read_excel() to reduce the memory footprint.

When you see "File not found" errors despite the file being visible in the explorer, double-check the path. Ensure there are no trailing spaces in the filename and that you are using the abfss:// protocol. If you are using a shortcut to another lakehouse, ensure the service principal or your user account has permissions to the source location.

If the data appears shifted or columns are missing, check for merged cells in the source Excel file. Spark cannot interpret merged cells; it will typically place the value in the first cell of the merge and leave the others as null. Unmerge all cells in the source file and fill the gaps before importing.

Frequently Asked Questions

Can I read multiple sheets from one Excel file?

Yes, but you must call the read command separately for each sheet or create a loop that iterates through a list of sheet names, appending each resulting DataFrame into a larger one using df.union().

Is there a limit to the size of the Excel file I can read?

While there is no hard limit, Excel files are not designed for Big Data. Files over 100MB can become extremely slow to parse. For larger datasets, it is highly recommended to export the data to CSV or Parquet before loading it into Fabric.

Do I need to install libraries every time I open the notebook?

No, if you use a Fabric "Environment." By adding the library to the environment and attaching that environment to your notebook, the library is pre-installed on the Spark cluster whenever the session starts.

Can I read password-protected Excel files?

Standard Spark-Excel and pandas readers cannot read encrypted or password-protected files directly. You must remove the password protection from the file before uploading it to the Lakehouse.

How do I handle dates that are imported as numbers?

Excel stores dates as integers (days since 1900). If your dates appear as numbers like 45123, you can use the from_unixtime function or a custom PySpark UDF to convert the Excel date integer into a standard SQL date format.

What is the difference between .xls and .xlsx?

.xls is the older binary format (Excel 97-2003), while .xlsx is the modern XML-based format. Most modern connectors support both, but .xlsx is generally more stable and compatible with current Spark libraries.