How to receive real-time data in excel using excel RTD and python?

1.6k Views Asked by At

I want to use excel as a front-end, which will continuously update multiple tables in real-time (every 2 seconds). I have a python program that prepares all the data tables, but it is running on some other server. I am storing python data in a Redis cache as a key-value pair. E.g.

'bitcoin':'bitcoin,2021-04-23 14:23:23,49788,dollars,4068890,INR,100000'

'doge':'doge,2021-04-23 14:23:23,0.2334,dollars,21,INR,1000'  

But, now I also want to use the same data in excel. Furthermore, I found that I can use excel RTD functions to update data in excel in real-time. But, I have no idea how will python send data to the excel RTD function. As per my understanding, I need to set up some RTD server in python and that will inject data to the excel RTD function. But how ?, I am not quite sure. Please help me with the required infrastructure or any code examples in python.

Note: I cannot use xlwings and pyxll(paid) for some reasons.

Thanking you in advance.

1

There are 1 best solutions below

0
On

You can do this with xlOil which is free (disclaimer: I wrote it). It allows you to write an async generator function in python which is presented to Excel as an RTD function.

As an example, the following code defines an RTD worksheet function pyGetUrl which will fetch a URL every N seconds. I'm not familiar with Redis, but I can see several async python client libraries which should be able to replace aiohttp in the below to access your data.

import aiohttp
import ssl
import xloil as xlo

# This is the implementation: it pulls the URL and returns the response as text
async def _getUrlImpl(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url, ssl=ssl.SSLContext()) as response:
           return await response.text() 

#
# We declare an async gen function which calls the implementation either once,
# or at regular intervals
#
@xlo.func(local=False, rtd=True)
async def pyGetUrl(url, seconds=0):
    yield await _getUrlImpl(url)
    while seconds > 0:
        await asyncio.sleep(seconds)
        yield await _getUrlImpl(url)

Rolling your own RTD server using Excel's COM interface and pywin32 may also be viable, you can look at this python example to see it done. You'll need to add a ProgId and CLSID to the windows registry so Excel can find your server; the example show you how to do this. Fair warning: this recent questioner was unable to make the example work. I also tried the example and had even less luck, so some debugging may be required.