我一直在玩耍并学习如何以编程方式制作 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
它对用户不太友好,但我设法使它工作,除了我无法检索默认的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()
}
关于为什么它不起作用的任何想法?非常感谢。
aluckdog
一只萌萌小番薯
随时随地看视频慕课网APP
相关分类