Yes, you can read Excel files in Databricks by using the built-in Spark "spark-excel" package or the Delta Lake connector, which allows you to load data from .xlsx or .xls formats directly into a Spark DataFrame for analysis. This process requires adding a dependency to your cluster or notebook to enable the file format support. Once configured, you can use simple commands to read the file and begin processing the data within the Databricks environment.
What You'll Need
- A Databricks workspace with a configured cluster (Standard or Premium tier recommended for file handling).
- Access to the Excel file you wish to import, either stored in DBFS (Databricks File System), Azure ADLS Gen2, or AWS S3.
- Admin or Editor permissions on the Databricks workspace to install library packages.
- Basic familiarity with Scala, Python (PySpark), or SQL within the notebook interface.
Step-by-Step
- Install the required library. Because Databricks does not include Excel reading capabilities by default, you must add the appropriate package to your cluster. Navigate to the Libraries tab in your cluster settings. Click "Install New" and enter the package name. For modern Excel (.xlsx) files, use the package
com.crealytics:spark-excel_2.12:0.13.7(adjust the version number based on your Spark version). If your cluster is running on a specific Databricks Runtime version, you may also use the Delta Lake connector packageio.delta:delta-core_2.12:2.0.0which includes Delta and Parquet reading capabilities, though for raw Excel, the spark-excel package is the direct solution. Click Install to proceed. The cluster will restart automatically to apply the changes. - Verify the installation. Once the cluster restarts, open a new notebook or switch to an existing one connected to this cluster. Create a simple test cell to ensure the library is available. For example, in a Python notebook, run
%load_ext sparkmagic.kerneldp(if not already loaded) or simply try importing the class in a Python cell:from com.crealytics.spark.excel import ExcelSparkSession. If no errors appear, the library is successfully installed and ready to use. - Prepare your file path. Identify where your Excel file is located. If it is in the DBFS root (mounted cloud storage), the path will start with
/dbfs/. If it is in Azure Blob Storage, the path will beabfss://container@storageaccount.dfs.core.windows.net/path/to/file.xlsx. If it is in AWS S3, the path will bes3a://bucket-name/path/to/file.xlsx. Ensure the path is enclosed in triple quotes to handle spaces correctly, e.g.,path = "/dbfs/mnt/excel_data/sales_report.xlsx". - Read the Excel file into a DataFrame. Use the SparkSession.read.format method to load the data. In a Python (PySpark) notebook, the syntax looks like this:
df = spark.read.format("com.crealytics.spark.excel") .option("header", "true") .option("inferSchema", "true") .load("/dbfs/mnt/excel_data/sales_report.xlsx")Settingheaderto "true" tells Spark that the first row contains column names. SettinginferSchemato "true" allows Spark to automatically detect the data type of each column (string, integer, double, etc.). This step may take a few moments depending on the file size. - Verify the loaded data. To ensure the file was read correctly, display the schema and a sample of the data. Run
df.printSchema()to see the inferred data types. Rundf.show(5)to display the first five rows. Check that the column names match your expectations and that the data types look accurate. You can also rundf.count()to verify that the total number of rows matches the row count in the source Excel file. - Perform data manipulation. Now that the data is in a Spark DataFrame, you can perform standard data transformation tasks. For example, to filter rows where a specific column is greater than a threshold, use the
filtermethod. To select specific columns, use theselectmethod. You can also write the data to a Delta table for long-term storage by runningdf.write.format("delta").mode("overwrite").save("/dbfs/mnt/delta/sales_data").
Common Mistakes
- Incorrect package versions. A frequent issue arises when using a package version that is incompatible with the Databricks Runtime version or the Scala version of the cluster. For instance, if your cluster is running Spark 3.2, you must use a spark-excel package version that targets Scala 2.12. If you use a package built for Scala 2.13, the installation will fail. Always check the compatibility matrix for the package you are installing.
- Missing headers. If the Excel file does not have a header row, or if the header row contains data that looks like a header, the schema inference may create incorrect column names. You can explicitly set the column names using the
option("columnNameOfCorruptRecord", "_corrupt_record")pattern, but often it is better to ensure your source Excel file is clean. If the file has no header, set the option.option("header", "false")and specify column names manually if needed. - Ignoring data type inference. By default, Spark may infer all columns as strings, which can lead to performance issues or errors when trying to perform mathematical operations on numeric columns. Always rely on the
inferSchemaoption or explicitly cast columns to their correct types after reading the data usingdf = df.withColumn("price", df["price"].cast("Double")). - Large file handling. Attempting to read a massive Excel file (hundreds of megabytes or gigabytes) into a single DataFrame can cause memory pressure on the driver node. If you encounter OutOfMemory errors, consider splitting the file into smaller chunks or using a tool like Apache POI to pre-process the file before loading it into Spark.
Tips
- Use Delta Lake for intermediate storage. It is highly recommended to write the loaded Excel data to a Delta table immediately after reading it. Delta Lake provides ACID transactions, schema enforcement, and optimized performance for subsequent queries. This creates a pipeline where you read legacy Excel files once and then query the optimized Delta table for all future analysis.
- Leverage the caching mechanism. If you plan to query the same DataFrame multiple times in a notebook session, use the
df.cache()method. This stores the DataFrame in memory (or disk if memory is full), significantly speeding up repeated operations on the data. - Check for corrupt rows. Excel files can sometimes contain rows with varying numbers of columns or malformed data at the end of sheets. The spark-excel package allows you to handle these errors gracefully by setting the
modeoption toPERMISSIVE(the default) orDROPMALFORMED. This prevents the entire read operation from failing due to a single bad row. - Optimize for performance. When reading large files, consider using the
maxRowsInMemoryoption if you only need to process a subset of the data. This helps limit the amount of data held in memory at any given time.
Troubleshooting
If you encounter errors during the reading process, follow this troubleshooting sequence to isolate the issue.
Cluster restart failed. If the cluster does not restart automatically or restarts with errors, check the cluster logs. Navigate to the cluster details page and look for the "Logs" tab. Open the driver log. If you see errors related to the new library installation (e.g., class not found), ensure you selected the correct package name and that the Databricks Runtime version supports it. Sometimes, simply restarting the cluster one more time resolves transient issues.
ClassNotFoundException. If you run your code and receive a java.lang.ClassNotFoundException for the Excel class, it means the library was not loaded correctly. This usually happens if the cluster was running when you installed the package. Stop the cluster, install the package again, and then start it. Alternatively, ensure you are using the correct Scala version for the package.
Path not found errors. If you see org.apache.hadoop.fs.PathNotFoundException, verify the file path string. Common mistakes include missing slashes, typos in the storage account name, or attempting to access a file in a bucket that the service principal or user does not have permission to read. Check your access controls in the cloud storage provider (Azure or AWS).
Data types are all strings. If the schema shows all columns as string, check the inferSchema option. Sometimes, if the Excel file contains mixed data types in a single column (e.g., numbers and text), Spark defaults to string. You can manually cast columns: df = df.withColumn("amount", df["amount"].cast("DecimalType(10,2)")).
Frequently Asked Questions
Can I read Excel files directly from a URL?
Generally, no. Spark's file system connectors (like the one used for Excel) typically require local or cloud storage paths (like DBFS, S3, or ADLS). You cannot point the load() method directly to a web URL (http/https) unless you first download the file to a local or storage location and then reference that path.
Does Databricks support .xls (older format) files?
Yes, the spark-excel package supports both .xls and .xlsx formats. However, .xls files are older binary formats that can be more complex to parse. If you are working with legacy .xls files, ensure the package version is stable and consider converting them to .xlsx for better performance and compatibility.
How do I handle multiple sheets in one Excel file?
By default, the spark-excel package reads the first sheet. To read a specific sheet, use the sheetName option: .option("sheetName", "Sheet2"). If you want to combine data from multiple sheets, you must read each sheet into its own DataFrame and then use the union or unionAll method to append them together.
Is it better to convert Excel to CSV first?
For very large datasets, yes. CSV is a text-based format that Spark reads very efficiently. Converting Excel to CSV reduces the overhead of the Excel parser. However, for medium-sized files or when preserving complex formatting (like merged cells or formulas), reading directly from Excel is more convenient.
Why does the read operation take a long time?
Reading Excel files is inherently slower than reading Parquet or CSV files. The parser must iterate through the binary data and reconstruct the schema. If the file is very large, the operation will take time. Additionally, if inferSchema is enabled, Spark must inspect every row to determine the data type, which adds to the processing time.
Can I use SQL to query the Excel data?
Yes. Once you have loaded the Excel file into a DataFrame, you can register it as a temporary view using df.createOrReplaceTempView("sales_data"). After that, you can run standard SQL queries within your notebook using %sql or the spark.sql() method.