目前我正在通过Python脚本管理与Excel文件的SQL连接。该脚本使用xlwings来读取和写入工作簿。不幸的是,只有'阅读'部分正在发挥作用。今天我已经梳理了Stackoverflow很长一段时间,似乎没有人有这个确切的问题。以下是我在相关的Python脚本中编写的一些调试代码(它作为UDF存在于工作表上,我试图写入的工作表是不同的)。我不是非常有Python或xlwings经历却又如此随意抱怨的结构/语法:)xlwings在Excel 2010中向单元格写入问题
@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调用约定')我没有触及加载项代码,因为与模块不同,设置不在文件中处理。我在xlwings功能区中输入的设置都是准确的。
当前设置:
操作系统:Windows Server 2008 R2企业版(测试这里因受到限制,脚本将不会在这里部署)
Python版本/发行版:2.7/Anaconda2
xlwings版本:0.11.4
Excel版本:2010 v 14.0.7182.5000(32位)
编辑:有趣的是,当我第一次打开该文件(后更新链接&打“继续”过时的链接),与细胞UDF显示s“状态:好”。如果我双击单元格以重新评估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的运行,就像我可以。