11

I'm trying to embed an interactive plotly (or bokeh) plot into excel.

To do this I've tried the following three things:

  1. embed a Microsoft Web Browser UserForm into excel, following:

How do I embed a browser in an Excel VBA form?

This works and enables both online and offline html to be loaded

  1. creating a plotly html

'''

import plotly
import plotly.graph_objects as go


x = [0.1, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
y = [i**2 for i in x]

fig = go.Figure()

fig.add_trace(go.Scatter(x=x, y=x, mode='markers', name="y=x", marker=dict(color='royalblue', size=8)))
fig.add_trace(go.Scatter(x=x, y=y, name="y=x^2", line=dict(width=3)))

plotly.offline.plot(fig, filename='C:/Users/.../pythonProject/test1.html')
  1. repointing the webbrowser object in excel using .Navigate to the local plotly.html. Banner pops up with

".... restricted this file from showing active content that could access your computer"

clicking on the banner, I run into this error:

enter image description here

The same HTML can be opened in a browser.

Is there any way to show interactive plots in excel?

vestland
  • 55,229
  • 37
  • 187
  • 305
dusio
  • 480
  • 5
  • 18
  • Correct, the excel webbrowser will open html, but fails when opening the plotly created "test1.html". However, "test1.html" can be opened in a browser (chrome, IE etc). In IE one needs to enable ActiveX controls, but otherwise it works fine. – dusio Dec 30 '20 at 13:28
  • The problem occurs when the HTML trying to use the JavaScript https://cdn.bokeh.org/bokeh/release/bokeh-2.2.3.min.js – Vignesh Dec 31 '20 at 02:47
  • You have to enable Macros (and JS) in Microsoft Excel! – anurag Dec 31 '20 at 11:40
  • 1
    Can you share the plotly html file? I would like to make some tests. – FaneDuru Jan 01 '21 at 17:47
  • I know this isn't the answer you're looking for but you could try [Microsoft Power BI](https://powerbi.microsoft.com/en-us/), load in your Excel data, and then add your custom Plotly code. – Jacob K Jan 01 '21 at 20:49
  • Is there a way we can exactly replicate your problem? I.e. do we need the html file for example? Also, what happens in step 3 after you click `yes` to running scripts? – QHarr Jan 03 '21 at 04:18
  • @dusiod https://www.wikihow.com/Enable-JavaScript-in-Internet-Explorer Please try this – Vignesh Jan 03 '21 at 14:27
  • 1
    @QHarr to replicate the HTML one needs to run the code in step 2 "creating a plotly html" above, this will save down the HTML to a defined location. Next is to load into excel, at which point the error above appears, clicking "yes" gives a second error "Plotly is undefined" – dusio Jan 04 '21 at 21:40
  • So what was wrong with letting the user use plotly in a browser? – S Meaden Jan 06 '21 at 12:02
  • @dusiod I know i was late to give an answer but still managed to give you an easy working and fully interactive solution https://stackoverflow.com/a/65678371/10849457 – Vignesh Jan 12 '21 at 05:23

4 Answers4

1

As mentioned by @jerlich, Excel blocks javascript. You should try the workaround they linked if you want full interactivity.

If you want at least some degree of controllability or interactivity, try using xlwings. With excel buttons, you can still have some communication between Excel and Python (including reading data and sending graphs).

The limitations are:

  • Only being able to use data entries and buttons, instead of the default plotly interactive features. Many could be replicated, but it would be more work.
  • It will only work on a computer you can set up your python script on (however, it looks like xlwings pro allows you to store your program inside the file)
  • It seems you will need to pass plotly graphs by saving and then adding the figure, because directly passing them requires xlwings pro. Direct passing without pro is possible with MatPlotLib.

Plotly guide to making interactive(ish) graphs

xlwings docs on MatPlotLib and Plotly graphs

thshea
  • 1,048
  • 6
  • 18
1

I like your question! And I'd wish I could give you a better answer, but It seems that the only way you can achieve anything remotely resembling an interactive plotly plot would be to use pyxll and follow the steps outlined under Charts and plotting / Plotly including a plot function like this:

from pyxll import xl_func, plot
import plotly.express as px

@xl_func
def plotly_plot():
    # Get some sample data from plotly.express
    df = px.data.gapminder()

    # Create a scatter plot figure
    fig = px.scatter(df.query("year==2007"),
                     x="gdpPercap", y="lifeExp",
                     size="pop", color="continent",
                     log_x=True, size_max=60)

    # Show the figure in Excel using pyxll.plot
    plot(fig)

This will produce the following plot:

enter image description here

Alas, this will not be a fully interactive plotly plot like we all know and love, since it's also stated on the very same page that:

The plot that you see in Excel is exported as an image so any interactive elements will not be available. To make a semi-interactive plot you can add arguments to your function to control how the plot is done and when those arguments are changed the plot will be redrawn.

But as far as I know this is as close as you'll get to achieving what you're seeking in your question. If you're not limited to Excel, but somehow limited to the realm of Microsoft, one of the commenters mentioned that you can unleash a fully interactive plotly plot in PowerBI. If that is an option, you should take a closer look at Is it possible to use R Plotly library in R Script Visual of Power BI?. This approach uses R though...

vestland
  • 55,229
  • 37
  • 187
  • 305
  • I am puzzled at pyxll, there is COM interoperability already within Python for free. pyxll requires money. – S Meaden Jan 06 '21 at 12:04
  • Fully interactive plot is also working, check here https://stackoverflow.com/a/65678371/10849457 – Vignesh Jan 12 '21 at 05:21
1

Finally, I have managed to bring the interactive plot to excel after a discussion from Microsoft QnA and Web Browser Control & Specifying the IE Version

To insert a Microsoft webpage to excel you have to change the compatibility Flag in the registry editor

Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\ClickToRun\REGISTRY\MACHINE\Software\Wow6432Node\Microsoft\Office\16.0\Common\COM Compatibility{8856F961-340A-11D0-A96B-00C04FD705A2}

Change the DWord 0 instead of 400

Now you can insert the web browser object to excel, Step by step details are here

Edit the HTML File generated from plotly manually by adding a tag for Using the X-UA-Compatible HTML Meta Tag

Originally generated HTML file from plotly looks like this

<html>
<head><meta charset="utf-8" /></head>
<body>

Modified HTML with browser compatibility

<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
</head>
<body>

After this, I can able to view the interactive plot in excel also able to do the interactions same as a web browser

Output

Macro used:

Sub Button4_Click()
ActiveSheet.WebBrowser1.Navigate "file:///C:/Users/vignesh.rajendran/Desktop/test5.html"
End Sub
Vignesh
  • 1,553
  • 1
  • 10
  • 25
  • This sounds awesome! But I can't get it to work on my end. I'm getting `Run Time Error 438 - Object doesn't support this property or method.` I'm running it on Windows 10 in an `.xlsm` file. Would you care to share some more details about your setup? – vestland Jan 12 '21 at 21:32
  • @vestland I am also running in win10 , i have kept my .xlsm file here -> https://gofile.io/d/XaPTSl and python code for generating html here -> https://gofile.io/d/Jvj3nd. if you need anything feel free to ask. – Vignesh Jan 13 '21 at 05:12
  • @Vignesh, This is awesome! Thank you so much, the simplest fixes are sometimes the hardest - I have no idea how you found that but it works! I tried to reactivate / reassign the bounty but the option is not appearing for me. – dusio Jan 13 '21 at 06:37
  • @vestlands, i'm running Win10, Office 2019 – dusio Jan 13 '21 at 06:45
  • @Vignesh Would you please consider describing in detail how you go from an empty Excel file to a working solution? I assume that would be great for other readers as well. And we're not too fond about links to external files and datasets in here either. So a completely working solution (perhaps not the complete html though :-) without links that might not work in a year or so would be great. If you're willing to put in a little extra effort here, I'll see what I can do about that bounty! – vestland Jan 13 '21 at 19:50
  • @vestlands, steps are: 1. to get a WebBrowser* object working in excel. https://stackoverflow.com/questions/19600586/excel-vba-create-an-embedded-webbrowser-and-use-it 2. create plotly HTML, and modify as above 3. repoint the WebBrowser object to the modified plotly HTML (as per Vignesh's example above) *if the webbrowser doesn't work, google it and you'll need to change an entry in the registry as MS disabled this feature In either case Vignesh deserves the bounty... ;) – dusio Jan 14 '21 at 01:35
  • 1
    @vestland I have posted it in a Blog here https://vikebot.blogspot.com/2021/01/creating-interactive-plotly-in.html as its a big story to post here. try it and give me a feedback – Vignesh Jan 14 '21 at 06:01
  • @Vignesh This works pretty great! I will however urge you to make the necessary edits to your SO post to make it reproducible. The only thing you're missing is really the guidance on how to insert the web object and how to make the necessary changes to registry. And you should perhaps also specify that the element you're reassigning values for in the registry is `Compatibility Flags`. If you're willing to do that, the bounty is yours. After all, SO bounty is for SO answers =). In any case, thank you for an insightful answer to a question that a lot of us in here were struggling with! – vestland Jan 14 '21 at 08:07
  • @vestland added registry compatibility details and the Blog Link to the post. Hope it was useful to everyone – Vignesh Jan 14 '21 at 13:57
0

Interactive plots require javascript to work. Excel, for security reasons, blocks that javascript. You can put a static image easily into excel.

The challenge of including javascript in excel has been addressed in this question: How can I use JavaScript within an Excel macro?

jerlich
  • 340
  • 3
  • 12
  • Hi @jerlich, as a disclaimer I'm not (yet) familiar with COM objects, reviewed the linked answer but I do not see how to leverage it for this issue, would you please outline the steps to follow? – dusio Jan 05 '21 at 03:28