本文介绍了当Excel加载项运行'RunPython()'时,Workbook.caller()引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现xlwings是Excel和Python之间的桥梁,是一个非常出色的项目.因此,我将其应用于我的excel插件开发.

I found xlwings is a very exceptional project as a bridge between Excel and Python. So I am applying it to my excel addin development.

但是我遇到了一些问题.

But I got some problem.

当excel addin调用python模块时,Workbook.caller()不会返回Workbook对象(addin工作簿本身)!只是错误!

When excel addin calls python module, the Workbook.caller() does not return Workbook object(addin workbook itself)! Just Error!

我代替了Workbook.caller(),而是使用了"Workbook()",并传递了当前ActiveWorkbook的名称".但是在那种情况下,恐怕'Optimize_connection = true'可能会引发内存垃圾问题!

Instead of Workbook.caller(), I make use of 'Workbook() passing by 'Current ActiveWorkbook's name'. But in that case, I'm afraid that 'Optimize_connection= true' may raise memory garbage issue!

(如果VBA中的"IsAddin"属性处于关闭状态,则它运行得很好)

(If 'IsAddin' property in VBA is off, then it runs very well)

有没有人可以帮助我?

谢谢.

推荐答案

以下是一种解决方法,可获取调用Python代码的Excel加载项:

Here's a work-around to get the Excel add-in that's calling Python code:

import mock
import platform
import xlwings
from   xlwings import Workbook

def get_add_in():
    if platform.system() == 'Windows':
        # Workbook.caller crashers instead of returning the add-in
        get_add_in_caller_on_windows()
    else:
        return Workbook.caller()

@mock.patch('xlwings.Sheet.active')
def get_addin_caller_on_windows(mock_active):
    # The xlwings.Sheet.active method is mocked because the add-in has no
    # active worksheet.
    xl_app = xlwings.xlplatform.get_xl_apps()[0]
    return Workbook(xl_workbook=xl_app.ThisWorkbook)

它与以下版本的Python 3.4和xlwings 0.6.4兼容:

It works with Python 3.4 and xlwings 0.6.4 on:

  • 带有Excel 2013的Windows 8.1
  • 用于Mac 2011的带有Excel的OS X 10.10(Yosemite)

这篇关于当Excel加载项运行'RunPython()'时,Workbook.caller()引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 19:45