I want to create a macro in Excel that calls my python code and outputs some charts from matplotlib and pandas to the same Excel Sheet in real time. Is there a way to output to Excel in real time without closing the Excel document?
I have tried some stuff but they only let you create new documents, create new sheets, and work on closed documents to output into Excel.
I expect outputs of charts made in pandas and matplotlib to be shown in Excel when done.
Absolutely. Check out xlwings for free which allows you to run code against an open workbook.
What code you want to execute is up to you, but a simple example would be:
import xlwings as xw
wb = xw.Book('test.xlsx')
worksheet = wb.sheets('Tab1');
worksheet.range('A1').value = "Hello There';
That will get you a workbook in realtime where the cell A1 is updated to 'Hello There' of course you can do much more like generate the graph in panda, and then insert over cells, etc.
Andrew!
To have your Excel file run a python code, you'll need to create a shell object to run your Python.exe - responsible for compiling and running your actual code, alongside with your .py script.
Option Explicit
Sub RunPythonScript()
Dim objShell As Object
Dim PythonExe, PythonScript As String
'' Create a new Object shell.
Set objShell = VBA.CreateObject("Wscript.Shell")
'' Change the Pyhton Executable path to what's on your computer
'' USE TRIPLE QUOTES WHEN FILE PATH CONTAINS SPACES.
PythonExe = """C:\Program Files (x86)\Microsoft Visual
Studio\Shared\Python36_64\python.exe"""
'' Change the script string to the path of your .py file you want to run
PythonScript = ""
'' Run the Python Script
objShell.Run PythonExe & PythonScript
End Sub
As for having matplotlib and pandas update the sheet itself, I believe the best way is to handle these steps in your Python code.
In my humble opition, you would be best of performed the whole process under your python code, but this is a way to tie it to your Excel.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.