|
| 1 | +# Read Excel Files in Spark and Pandas |
| 2 | + |
| 3 | +This module demonstrates two approaches to read Excel files within Spark environments like **OCI Data Flow**, **Databricks**, or **local Spark clusters**. |
| 4 | + |
| 5 | +--- |
| 6 | + |
| 7 | +## 1. Using `com.crealytics.spark.excel` |
| 8 | + |
| 9 | +This approach uses the **Spark Excel connector** developed by [Crealytics](https://github.com/crealytics/spark-excel). |
| 10 | +It supports `.xls` and `.xlsx` files directly within Spark DataFrames. |
| 11 | + |
| 12 | +### Requirements |
| 13 | + |
| 14 | +You must add the following JARs to your cluster classpath: |
| 15 | + |
| 16 | +- poi-4.1.2.jar |
| 17 | +- poi-ooxml-4.1.2.jar |
| 18 | +- poi-ooxml-schemas-4.1.2.jar |
| 19 | +- xmlbeans-3.1.0.jar |
| 20 | +- curvesapi-1.06.jar |
| 21 | +- commons-collections4-4.4.jar |
| 22 | +- commons-compress-1.20.jar |
| 23 | +- spark-excel_2.12-0.13.5.jar |
| 24 | + |
| 25 | +Download them from [Maven Central Repository](https://mvnrepository.com/). |
| 26 | + |
| 27 | +### Example |
| 28 | + |
| 29 | +```python |
| 30 | +excel_path = "/Volumes/test_data.xlsx" |
| 31 | + |
| 32 | +df = spark.read.format("com.crealytics.spark.excel") \ |
| 33 | + .option("header", "true") \ |
| 34 | + .option("inferSchema", "true") \ |
| 35 | + .load(excel_path) |
| 36 | + |
| 37 | +df.show() |
| 38 | +``` |
| 39 | +# Excel to Spark using Pandas |
| 40 | + |
| 41 | +This example demonstrates how to **read Excel files using Pandas**, optionally convert them to **CSV**, and then **load them into Spark** for further processing. |
| 42 | +It’s ideal for lightweight or pre-processing workflows before ingesting data into Spark. |
| 43 | + |
| 44 | +--- |
| 45 | + |
| 46 | +## Requirements |
| 47 | + |
| 48 | +Install the required dependencies via `requirements.txt`: |
| 49 | +- `pandas` |
| 50 | +- `openpyxl` |
| 51 | +- `xlrd` |
| 52 | + |
| 53 | +### Example |
| 54 | + |
| 55 | +```python |
| 56 | +import pandas as pd |
| 57 | + |
| 58 | +# Path to Excel file |
| 59 | +excel_path = "/Volumes/test_data.xlsx" |
| 60 | + |
| 61 | +# Read Excel file using Pandas |
| 62 | +df = pd.read_excel(excel_path) |
| 63 | + |
| 64 | +# Convert to CSV if needed |
| 65 | +csv_path = "/Volumes/test_data.csv" |
| 66 | +df.to_csv(csv_path, index=False) |
| 67 | + |
| 68 | +print(df.head()) |
| 69 | + |
| 70 | +# Load the CSV back into Spark |
| 71 | +spark_df = spark.read.csv(csv_path, header=True, inferSchema=True) |
| 72 | +spark_df.show() |
| 73 | + |
| 74 | +``` |
0 commit comments