Skip to content

Instantly share code, notes, and snippets.

@burque505
Created February 12, 2022 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burque505/c6469d451cf19592bd9e4b2d644226ba to your computer and use it in GitHub Desktop.
Save burque505/c6469d451cf19592bd9e4b2d644226ba to your computer and use it in GitHub Desktop.
Go-ole - word tables
package main
import (
"fmt"
"reflect"
"time"
ole "github.com/go-ole/go-ole"
"github.com/go-ole/go-ole/oleutil"
)
var pl = fmt.Println // Monkeys hate typing
var mpp = oleutil.MustPutProperty
var mgp = oleutil.MustGetProperty
var mcm = oleutil.MustCallMethod
func main() {
ole.CoInitialize(0)
defer ole.CoUninitialize()
unknown, _ := oleutil.CreateObject("Word.Application")
word, _ := unknown.QueryInterface(ole.IID_IDispatch)
mpp(word, "Visible", true)
documents := mgp(word, "Documents").ToIDispatch()
document := mcm(documents, "Add").ToIDispatch()
paragraphs := mgp(document, "Paragraphs").ToIDispatch()
paragraph := mcm(paragraphs, "Add").ToIDispatch()
rnge := mgp(paragraph, "Range").ToIDispatch()
mpp(rnge, "Text", "This is a Word document created with Go and go-ole.")
mcm(rnge, "InsertAfter", "\nIt is being programmed by a primate. A fat one.")
mcm(rnge, "InsertParagraphAfter")
lastPara := mgp(paragraphs, "Last").ToIDispatch()
lastRange := mgp(lastPara, "Range").ToIDispatch()
tables := mgp(document, "Tables").ToIDispatch()
table1 := mcm(tables, "Add", lastRange, 5, 11).ToIDispatch()
// Created an object, so it needs 'ToIDispatch'
mpp(table1, "Style", "Table Grid")
tableRange := mgp(table1, "Range").ToIDispatch()
fmt.Println(reflect.TypeOf(tableRange))
cell1 := mcm(table1, "Cell", 1, 1).ToIDispatch()
fmt.Println(reflect.TypeOf(cell1))
cell1Range := mgp(cell1, "Range").ToIDispatch()
mcm(cell1Range, "InsertAfter", "Gross")
rows := mgp(table1, "Rows").ToIDispatch()
rowCount := mgp(rows, "Count")
numRows := rowCount.Val
pl(numRows)
cols := mgp(table1, "Columns").ToIDispatch()
colCount := mgp(cols, "Count")
numCols := colCount.Val
pl(numCols)
lastCell := mcm(table1, "Cell", numRows, numCols).ToIDispatch()
lastCellRange := mgp(lastCell, "Range").ToIDispatch()
mcm(lastCellRange, "InsertAfter", "Yuk.").ToIDispatch()
time.Sleep(5 * time.Second)
// mpp(document, "Saved", true)
mcm(document, "SaveAs", `C:\work\Word\monkey business.docx`)
mcm(document, "Close", false)
mcm(word, "Quit")
word.Release()
pl("Finished")
//ole.CoUninitialize() - took care of this with 'defer' above
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment