我一直在玩耍,学习如何以编程方式制作Word文档。我知道可以使用轻松完成pywin32
。这个简单的代码片段在新的Word文档中检索默认的Visual Basic“代码”。
import win32com.client
word = win32com.client.Dispatch("Word.Application")
word.Visible = True
document = word.Documents.Add()
document.VBProject.Name = "TEST"
wordModule = document.VBProject.VBComponents("ThisDocument") # WORKS
input()
然后,您可以将VB代码添加到wordModule
。
我想用Golang做同样的事情。Go的OLE绑定,代码在Github上-> https://github.com/go-ole/go-ole
它对用户的友好程度有所降低,但我设法使其正常工作,除了我无法检索default VBComponents
。
默认代码位于“ ThisDocument”中,并且可以用简单的python代码检索,document.VBProject.VBComponents("ThisDocument")
除了它在Go中不起作用外。您可以在下面的代码中看到我尝试使用多种方式获取“ ThisDocument”,而没有成功。每次,错误消息是panic: Unknown name.
// +build windows
package main
import (
"fmt"
ole "github.com/go-ole/go-ole"
"github.com/go-ole/go-ole/oleutil"
)
func main() {
defer ole.CoUninitialize()
ole.CoInitialize(0)
unknown, _ := oleutil.CreateObject("Word.Application")
word, _ := unknown.QueryInterface(ole.IID_IDispatch)
oleutil.PutProperty(word, "Visible", true)
documents := oleutil.MustGetProperty(word, "Documents").ToIDispatch()
document := oleutil.MustCallMethod(documents, "Add").ToIDispatch()
vbproject := oleutil.MustGetProperty(document, "VBProject").ToIDispatch()
oleutil.PutProperty(vbproject, "Name", "TEST")
// oleutil.MustCallMethod(vbproject, "VBComponents", "ThisDocument").ToIDispatch() --> panic: Unknown name.
// oleutil.MustGetProperty(vbproject, "VBComponents", "ThisDocument").ToIDispatch() --> panic: Unknown name.
// vbcomponents := oleutil.MustGetProperty(vbproject, "VBComponents").ToIDispatch()
// oleutil.MustGetProperty(vbcomponents, "ThisDocument").ToIDispatch() --> panic: Unknown name.
var input string
fmt.Scanln(&input)
oleutil.PutProperty(document, "Saved", true)
oleutil.CallMethod(documents, "Close", false)
oleutil.CallMethod(word, "Quit")
word.Release()
}
有什么想法为什么不起作用?非常感谢。
原来"github.com/go-ole/go-ole"
在使用时存在错误ForEach
。VBComponets
是Collection
,因此您必须按照Microsoft doc所述进行迭代
使用VBComponents集合可以访问,添加或删除项目中的组件。组件可以是表单,模块或类。VBComponents集合是一个标准集合,可以在For ... Each块中使用。
此行-> https://github.com/go-ole/go-ole/blob/master/oleutil/oleutil.go#L106应该替换为
newEnum, err := disp.CallMethod("_NewEnum")
现在它可以按预期工作了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句