Excel-Python App for Non-Pythonists | by Jesko Rehberg | Towards Data Science

Motivation:
Oftentimes we conduct impressive Python analysis, but all that our colleagues are asking for is to receive the final results within Excel. Many of our colleagues do not want to work with Jupyter Notebook, Python scripts and the like. They just want to stick with their beloved spreadsheet tool (like Microsoft Excel, to call it by name). In this story we will learn how to build such an Excel solution, which uses Python in the background. So our non Pythonists colleagues can start the Python code directly out of Excel, without any Python knowledge necessary (also without dealing with any technical issues like package installing or version troubleshooting).
Solution:
Let’s now examine how to run Python from within Excel step by step.
First of all, you need to pip install xlwings. In case you have not yet installed Xlwings, please do so now, e.g. via pip install:
pip install xlwings
Afterwards we import Xlwings for a short test:
import pandas as pdimport xlwings as xwdf = pd.read_excel('InputOutput.xlsm')xw.view(df)
In contrast to Pandas, Xlwings opens this Excel file (.view) so we can have a look at the dataframe directly in an Excel spreadsheet. This can be very handy when inspecting a big dataframe (more convenient than going through a big dataframe directly in a Juypter Notebook cell, especially for cross checking lots of calculations).
Thanks to Xlwings we can do quite everything in a Jupyter Notebook and finally write the dataframe back into an Excel sheet. The basic concept is simply to write your code into a main function. Let’s have a look at a simple example first:
# Make sure, that the Excel file is located in the same path as this file.import pandas as pdimport xlwings as xwdef main():    wb = xw.Book.caller()    sht = wb.sheets['Input']    df = sht.range('A1').options(pd.DataFrame, header=1, index=False, expand='table').value    counter = []# add Counter starting from one until max counter is reached     for index, row in df.iterrows():        for x in range(int(row['Counter'])):            counter.append(x+1)# duplicate the rows according to Item specific max counter    df = df.loc[df.index.repeat(df.Counter)]# Add the counter number per row    df['CounterDuplRow'] = counter    df['Total']=(df['Column A']+df['Column B'] + df['Column C']) *df['CounterDuplRow']    df2 = df.sort_values("Total").groupby("Item", as_index=False).last()    shtout = wb.sheets['Output']    shtout.range('a1').options(pd.DataFrame, index=False).value = df2@xw.funcdef hello(name):    return f"Hello {name}!"if __name__ == "__main__":    xw.Book("InputOutput.xlsm").set_mock_caller()    main()# in case this Jupyter Notebook is working well, you can download it as a Python file (.py)# to do so, just click on "file" in the menu above and choose "download as py"
Please note that the Excel file must be located in the same folder as your Jupyter Notebook to work well. What this script basically does is to take the input from Excel’s Input tab, loop through it and does some calculations (for training purpose we have added a loop). The result dataframe gets written back into the same Excel file, into the tab “Output”:
If everything is working well, we can save our Jupyter Notebook as a Python script (just click on “file” in the Jupyter Notebook menu and choose “download as py”), and make sure to give it the same name as our Excel file:
We are now able to start the calculations in a Jupyter Notebook, reading and writing the dataframe out of Excel. So far, nothing new. But thanks to Xlwings we can now add a VBA macro into Excel, so we can start the Jupyter Notebook out of Excel. Okay, that’s getting a little bit more interesting. But what we are really looking for is to hand over an Excel-Python App to our colleagues, without the need for them to set up Python (or a Xlwings Add-in in Excel) on their machines. We will now learn how to get there. Our solution is to export all the required Python packages via PyInstaller. Again, if you do not already have PyInstaller, please install it now:
pip install pyinstaller
Then we can use PyInstaller to create all the needed files for our Excel-Python App. We just have to go into our terminal, go to the same folder where our two files (InputOutput.py and InputOutput.xslm) are located and enter:
pyinstaller –-onefile InputOutput.py
Depending on your environment, this might take some time. But in the end the terminal should tell that an Exe has successfully been built:
Now when we look into our folder again, we will find all the necessary packages deployed for our Excel-Python App:
And in the folder “dist” we will find the exe file:
Now you can doubleclick this executable InputOutput.exe and afterwards you can check your InputOutput.xlsm: you will see that the Output tab has been calculated. That means, you could already hand over the complete folder “InputOutput” to your colleagues, who do not have Python installed on their computers. You will see that they can also start the exe and that they will receive the same Output tab in Excel as you just did.
To make it even more convenient for our colleagues, we will do a last modification. We will add a little VBA in Excel, so our colleagues can start the code directly out of Excel:
Sub ExeExecute()‘ Windows-Editor startDim TaskID As LongTaskID = Shell(“C:\Users\Jesko\InputOutput\dist\InputOutput.exe”, vbNormalNoFocus)End Sub
Congratulations, we have successfully created a complete Excel-Python App which runs out of Excel even on computers without any additional Python installation necessary. You can find the Jupyter Notebook and Excel example in my Github. Many thanks for reading, hope this was supportive! Any questions, please let me know. You can connect with me on LinkedIn or Twitter.
Originally published on my website DAR-Analytics.