xlwings在Excel 2010中向单元格写入问题

目前我正在努力通过Python脚本pipe理与Excel文件的SQL连接。 该脚本使用xlwings读取和写入工作簿。 不幸的是,只有“阅读”一块运作。 我已经梳理了一段时间Stackoverflow今天没有人似乎有这个确切的问题。 这里是我在相关的Python脚本中写的一些debugging代码(它作为UDF存在于工作表上,我试图写入的表是不同的)。 我对Python或xlwings没有太多的经验,所以可以自由地抱怨结构/语法:)

@xw.func def compatTest(): #use active workbook wb = xw.Book.caller() #does the sheet Notes exist? if wb.sheets['Notes']: status = "Status: " #does A1 in Notes have a value? if wb.sheets['Notes'].range('$A$1').value: status += "Good" #Can we write to the specified empty cell? try: wb.sheets['Notes'].range('$E$1').value = 'something' #Nope :( except Exception as e: status = e.message return status + "can't write :(" #This return statement shouldn't evaluate, just casting a wide net here return status + " " + str(wb.sheets['Notes'].range('$A$1').value) else: #A1 in notes is blank status += "Bad" wb.sheets['Notes'].range('$E$1').value = 'nothing' return status + " " + 'blank :(' 

单元格中的UDF输出:“不能写:(” – 这意味着错误信息没有被返回。

我正在使用xlwings 0.11.4加载项和VBA引用(我没有使用VBA模块,因为它似乎与加载项重叠并生成VBA错误49'错误的DLL调用约定')。 我没有触及加载项代码,因为与模块不同,设置不在文件中处理。 我在xlwingsfunction区中input的设置都是准确的。

当前的设置:
操作系统:Windows Server 2008 R2企业版(由于受到限制,此处不会部署脚本)
Python版本/发行版:2.7 / Anaconda2
xlwings版本:0.11.4
Excel版本:2010 v。14.0.7182.5000(32位)

编辑:有趣的是,当我第一次打开文件(更新链接和点击“继续”过时的链接后),与UDF单元格显示“状态:良好”。 如果我双击单元格来重新评估UDF,它将更改为“不能再写入:(”。
如果我将except块更改为以下内容:

  except: a = str(sys.exc_info()[0]) b = str(sys.exc_info()[1]) c = str(sys.exc_info()[2]) status = str(a + " \ " + b + " \ " + c) return status 

我得到:

 "<class 'pywintypes.com_error'> \ (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146827284), None) \ <traceback object at 0x0000000007B95708>" 

编辑#2:
奇怪的是,我可以使用xw.sub修饰器写入单元格:

 @xw.sub def SomeFunction(): wb = xw.Book.caller() wb.sheets['Notes'].range('B3').value = "hello world" 

该代码工作正常,但我宁愿尽可能通过UDF运行尽可能。

原来我误解了Excel中函数的行为和修饰器xw.func的使用 – 这将基本上将该代码块转换为Excel函数。 函数行为在这里描述:
https://support.microsoft.com/en-us/help/170787/description-of-limitations-of-custom-functions-in-excel
我曾希望完全绕过macros来减less开销,但令人伤心的是,使用Excel的固有限制阻止了这一点 – 函数不能修改任何其他工作簿的内容 。 我希望这可以节省别人几天工作的麻烦,尽pipe他们肯定是教育的。 如果任何人看到这一点,并可以build议一个可行的解决scheme给我的环境,你是不是欢迎。