【发布时间】:2015-05-09 10:11:06
【问题描述】:
我在尝试从 excel 调用 module.py 文件时不断收到此错误
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "F:\ana\module.py", line 6, in rand_numbers
wb = Workbook.caller() # Creates a reference to the calling Excel file
AttributeError: type object 'Workbook' has no attribute 'caller'
当我将 wb = Workbook.caller() 替换为 wb = Workbook() 时,我收到此错误
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "F:\ana\module.py", line 11, in rand_numbers
rand_num = np.random.randn(n, n)
File "mtrand.pyx", line 1341, in mtrand.RandomState.randn (numpy\random\mtrand\mtrand.c:11537)
File "mtrand.pyx", line 1454, in mtrand.RandomState.standard_normal (numpy\random\mtrand\mtrand.c:11839)
File "mtrand.pyx", line 142, in mtrand.cont0_array (numpy\random\mtrand\mtrand.c:1867)
TypeError: an integer is required
或者 [场景 2],我可以在使用 this sample code 时从 excel 调用 python 文件
from xlwings import Workbook, Sheet, Range, Chart
wb = Workbook() # Creates a connection with a new workbook
#wb = Workbook.caller()
Range('A1').value = 'Foo 1'
Range('A2').value = [['Foo 1', 'Foo 2', 'Foo 3'], [10.0, 20.0, 30.0]]
Range('A13').table.value # or: Range('A1:C2').value
Sheet(1).name
chart = Chart.add(source_data=Range('A2').table)
但是 excel 中的调用仅适用于 wb = Workbook() 而不是 wb = Workbook.caller()
我知道this API documentation update
module.py
import numpy as np
from xlwings import Workbook, Range
def rand_numbers():
""" produces std. normally distributed random numbers with shape (n,n)"""
wb = Workbook.caller() # Creates a reference to the calling Excel file
n = Range('Sheet1', 'B1').value # Write desired dimensions into Cell B1
rand_num = np.random.randn(n, n)
Range('Sheet1', 'C3').value = rand_num
VBA 代码
Sub MyMacro()
RunPython ("import module; module.rand_numbers()")
End Sub
testing.py(测试示例代码 - 场景 2)
from xlwings import Workbook, Sheet, Range, Chart
wb = Workbook() # Creates a connection with a new workbook
#wb = Workbook.caller()
Range('A1').value = 'Foo 1'
Range('A2').value = [['Foo 1', 'Foo 2', 'Foo 3'], [10.0, 20.0, 30.0]]
Range('A13').table.value # or: Range('A1:C2').value
Sheet(1).name
chart = Chart.add(source_data=Range('A2').table)
VBA 代码
Sub MyMacro()
RunPython ("import testing")
End Sub
【问题讨论】:
-
你能输入你正在运行的确切代码吗(
module.py和 VBA 宏?另外,python 文件是否与 excel 文件在同一目录中? -
添加代码;是的,所有文件都在同一个目录中
-
嗯,您正在运行最新版本的 xlwings?我刚刚尝试过,它适用于我的版本
0.3.2。我正在使用具有所有开箱即用设置的 Mac,并且刚刚使用pip重新安装了 xlwings。 -
看起来您确实在使用旧版本的 xlwings:打开命令提示符,输入
python,然后输入import xlwings和xlwings.__version__。 -
我下载了 anaconda,虽然 xlwings 附带 conda,但我必须更新 xlwings,因为附带的默认版本不是最新的,
conda install xlwings