首页 文章

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

提问于
浏览
1

目前,我正在通过Python脚本管理与Excel文件的SQL连接 . 该脚本使用xlwings读取和写入工作簿 . 不幸的是,只有“阅读”作品才有效 . 我今天已经梳理了Stackoverflow很长一段时间了,似乎没有人有这个确切的问题 . 以下是我在相关Python脚本中编写的一些调试代码(它作为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模块 not ,因为它看起来与加载项重叠并生成VBA错误49 'Bad DLL calling convention') . 我没有't touched the add-in code, as unlike the module the settings aren'吨在文件中处理 . 我在xlwings功能区中输入的设置都是准确的 .

当前设置:
操作系统:Windows Server 2008 R2 Enterprise(由于限制而在此处测试,此处不会部署脚本)
Python版本/发行版:2.7 / Anaconda2
xlwings版本:0.11.4
Excel版本:2010 v.14.0.7182.5000(32位)

Edit: 有趣的是,当我第一次打开文件时(更新链接并为过时的链接命中'Continue')后,带有UDF的单元格显示"Status: Good " . 如果我双击单元格以重新评估UDF,它将再次更改为"can't write :(" .
如果我将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>"

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

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

该代码工作得很好,但如果可能的话,我宁愿尽可能多地通过UDF运行 .

1 回答

  • 1

    事实证明我误解了Excel中函数的行为以及装饰器 xw.func 的使用 - 这实际上将该代码块转换为Excel函数 . 这里描述了函数行为:
    https://support.microsoft.com/en-us/help/170787/description-of-limitations-of-custom-functions-in-excel
    我曾希望完全绕过宏以减少开销,但遗憾的是使用Excel的固有限制阻止了这一点 - functions cannot modify the contents of any other piece of the workbook . 我希望这可以为其他人省去失去几天工作的麻烦,尽管他们肯定是有教育意义的 . 如果有人看到这个并且可以根据我的环境提出可行的解决方法,那么非常欢迎您 .

相关问题