To insert a table from Excel into a Delta table, you must first convert the Excel file into a format compatible with Spark (such as CSV or Parquet) or use a specific library like pandas or Spark-Excel to read the file, then use the df.write.format("delta").mode("append").saveAsTable("table_name") command. This process allows you to move static spreadsheet data into a high-performance Lakehouse architecture, enabling ACID transactions and scalable querying.

What You'll Need

  • An Excel file (.xlsx or .xls) containing the data you wish to import.
  • A Databricks workspace or an Apache Spark environment configured with Delta Lake.
  • Necessary permissions to write to the target database or schema.
  • The pandas library (for small to medium files) or the com.crealytics.spark.excel library (for large-scale Spark reads).
  • A defined schema for the target Delta table, or the ability to create one via schema evolution.

Step-by-Step

  1. Prepare the Excel Source Data: Before attempting the import, open your Excel file and ensure the data is in a clean, tabular format. Remove any merged cells, total rows at the bottom, or decorative headers. Ensure the first row contains clear, unique column names without spaces or special characters (e.g., use customer_id instead of Customer ID #), as Delta Lake column names have specific naming restrictions. Save the file and close it to avoid file-lock errors.
  2. Upload the File to Cloud Storage: Upload your Excel file to a location accessible by your Spark cluster. In Databricks, you can use the DBFS (Databricks File System) upload tool or upload the file to an S3 bucket or Azure Data Lake Storage (ADLS) container. Note the full path to the file, such as /dbfs/mnt/raw_data/sales_export.xlsx.
  3. Read the Excel File into a DataFrame: Depending on your file size, choose one of two methods. For smaller files, use pandas: import pandas as pd; pdf = pd.read_excel("/path/to/file.xlsx"); df = spark.createDataFrame(pdf). For larger files, use the Spark-Excel connector. You must first install the library via the cluster libraries tab. Then use: df = spark.read.format("com.crealytics.spark.excel").option("header", "true").load("/path/to/file.xlsx").
  4. Validate and Cast Data Types: Excel often assigns ambiguous data types. Check your DataFrame schema using df.printSchema(). If a column that should be an integer is listed as a string, cast it explicitly: from pyspark.sql.functions import col; df = df.withColumn("price", col("price").cast("double")). This prevents "Schema Mismatch" errors during the insertion process.
  5. Handle Missing Values: Excel files frequently contain empty cells which Spark reads as null. Decide if these should remain null or be replaced. To fill nulls with a default value, use: df = df.fillna({"status": "Unknown", "amount": 0}). This ensures data integrity in your Delta table.
  6. Insert Data into the Delta Table: Use the write API to move the data. If the table already exists and you want to add new rows, use the append mode: df.write.format("delta").mode("append").saveAsTable("your_database.your_table_name"). If you are creating the table for the first time, use mode("overwrite") or simply omit the mode to create it based on the DataFrame schema.
  7. Verify the Insertion: Run a SQL query to ensure the data was inserted correctly. Use SELECT count(*) FROM your_database.your_table_name to check the row count against your Excel sheet, and SELECT * FROM your_database.your_table_name LIMIT 10 to verify the content and formatting.

Common Mistakes

One of the most frequent errors is ignoring the column naming conventions of Delta Lake. Excel allows spaces, parentheses, and commas in headers, but Delta Lake (depending on the version and configuration) may throw an error or produce corrupted metadata if these are present. Always sanitize your headers to use underscores instead of spaces.

Another common mistake is failing to handle the "header row" correctly. If the header option is not set to true, Spark will treat your column names as the first row of data, leading to type mismatch errors (e.g., trying to put the string "Date" into a DateType column).

Users often forget to check for duplicate data. Since the append mode simply adds rows to the bottom of the table, running the import script twice will result in duplicate records. If you need to avoid duplicates, you should use the MERGE INTO command instead of a simple append.

Tips

For recurring imports, consider saving the Excel file as a CSV first. CSVs are natively supported by Spark and are significantly faster to read than .xlsx files, which require complex decompression and parsing. This reduces the compute resources needed for the job.

If your Excel file has multiple sheets, remember that the standard read command only pulls the first sheet. Use the dataAddress option in the Spark-Excel connector (e.g., .option("dataAddress", "'Sheet2'!A1")) to specify exactly which tab and range of cells to import.

To keep your Delta table performant after a large Excel import, run the OPTIMIZE command: OPTIMIZE your_table_name. This compacts the small files created during the write process into larger, more efficient files, speeding up future read queries.

Troubleshooting

If you encounter a "AnalysisException: A schema mismatch was detected" error, it means the columns in your Excel file do not exactly match the columns in the existing Delta table. You can resolve this by enabling schema evolution. Add .option("mergeSchema", "true") to your write command. This allows Delta Lake to automatically add new columns to the table schema if they exist in the Excel file but not in the table.

If the cluster fails to read the .xlsx file, check if the required library (like com.crealytics.spark.excel) is installed on all worker nodes. If using pandas, ensure the openpyxl engine is installed via pip (pip install openpyxl), as pandas requires it to read modern Excel files.

If you see incorrect data types (e.g., dates appearing as long integers), this is because Excel stores dates as the number of days since December 30, 1899. You will need to apply a mathematical transformation or use the to_date function in Spark to convert these numeric values back into a readable date format.

If the write operation is extremely slow, check the size of your DataFrame. If you are using spark.createDataFrame(pdf) with a massive pandas DataFrame, you are bottlenecking the process through the driver node. Switch to the native Spark-Excel reader to distribute the load across the cluster workers.

Frequently Asked Questions

Can I import only a specific range of cells from Excel?

Yes, if you use the Spark-Excel connector, you can use the dataAddress option to specify a range, such as 'Sheet1'!A1:G50, which tells Spark to ignore everything outside that specific block.

What happens if the Excel file is empty?

If the file is empty or contains only headers, the DataFrame will be empty. The append operation will complete successfully but will add zero rows to your Delta table.

Do I need to delete the Excel file after importing?

No, the import process reads the data and writes it into the Delta format on your storage. The original Excel file remains untouched in its source location.

Can I update existing rows in the Delta table using Excel?

A simple append will not update rows; it only adds new ones. To update existing records, you must load the Excel data into a temporary view and use the MERGE INTO SQL command to match records based on a primary key.

Is there a limit to how many rows I can import from Excel?

While Delta Lake can handle billions of rows, Excel itself has a limit of 1,048,576 rows per sheet. If your data exceeds this, you must split it across multiple sheets or move to a CSV/Parquet format.