简体   繁体   English

将Python实时输出到Excel

[英]Python output to Excel in real time

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. 我想在Excel中创建一个宏,该宏调用我的python代码,并从matplotlib和pandas实时输出一些图表到同一Excel Sheet。 Is there a way to output to Excel in real time without closing the Excel document? 是否可以在不关闭Excel文档的情况下实时输出到Excel?

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. 我已经尝试了一些方法,但是它们只允许您创建新文档,创建新工作表以及处理已关闭的文档以输出到Excel。

I expect outputs of charts made in pandas and matplotlib to be shown in Excel when done. 我希望完成后以Excel和pandas和matplotlib制作的图表输出。

Absolutely. 绝对。 Check out xlwings for free which allows you to run code against an open workbook. 免费检查xlwings ,它使您可以对打开的工作簿运行代码。

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. 这将为您实时提供一个工作簿,其中单元格A1更新为“ Hello There”。您当然可以做更多的事情,例如在熊猫中生成图形,然后在单元格上插入等等。

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. 要让您的Excel文件运行python代码,您需要创建一个外壳对象来运行Python.exe-负责编译和运行实际代码以及.py脚本。

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. 至于让matplotlib和pandas更新工作表本身,我相信最好的方法是在Python代码中处理这些步骤。

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. 以我谦卑的选择,最好在python代码下执行整个过程,但这是将其绑定到Excel的一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM