Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

databricks: writing spark dataframe directly to excel

Tags:

databricks

Are there any method to write spark dataframe directly to xls/xlsx format ????

Most of the example in the web showing there is example for panda dataframes.

but I would like to use spark dataframe for working with my data. Any idea ?

like image 512
mytabi Avatar asked Nov 29 '19 15:11

mytabi


1 Answers

I'm assuming that because you have the "databricks" tag you are wanting to create an .xlsx file within databricks file store and that you are running code within databricks notebooks. I'm also going to assume that your notebooks are running python.

There is no direct way to save an excel document from a spark dataframe. You can, however, convert a spark dataframe to a pandas dataframe then export from there. We'll need to start by installing the xlsxwriter package. You can do this for your notebook environment using a databricks utilites command:

dbutils.library.installPyPI('xlsxwriter')
dbutils.library.restartPython()

I was having a few permission issues saving an excel file directly to dbfs. A quick workaround was to save to the cluster's default directory then sudo move the file into dbfs. Here's some example code:

# Creating dummy spark dataframe
spark_df = spark.sql('SELECT * FROM default.test_delta LIMIT 100')

# Converting spark dataframe to pandas dataframe
pandas_df = spark_df.toPandas()

# Exporting pandas dataframe to xlsx file
pandas_df.to_excel('excel_test.xlsx', engine='xlsxwriter')

Then in a new command, specifying the command to run in shell with %sh:

%sh
sudo mv excel_test.xlsx /dbfs/mnt/data/
like image 155
Papa_Helix Avatar answered Oct 21 '22 06:10

Papa_Helix