AHK/CLR/OpenXml - Office docs w/o Office

Put simple Tips and Tricks that are not entire Tutorials in this forum
burque505
Posts: 628
Joined: 22 Jan 2017, 19:37

AHK/CLR/OpenXml - Office docs w/o Office

31 May 2018, 16:08

I've just used this for .docx so far, but it appears to be used extensively for .xlsx. Office not required!
Here's a very simple example for docx. I was able to open existing docs a long time ago, but it took me forever to be able to create one. I ran down a lot of blind alleys before I got there.
If you do a search for OfficeOpenXML, ooxml, or DocumentFormat.OpenXml you'll get tons of information.

Code: Select all

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.

; This requires DocumentFormat.OpenXml.dll be in the same directory.
; You may have to register it, but you shouldn't have to if
; it's in the same directory.

If (FileExist("SampleDoc2.docx"))
	FileDelete, SampleDoc2.docx

#Include <CLR>

vb =
(
	Imports System.IO
	Imports System.Runtime
    Imports DocumentFormat.OpenXml.Packaging
    Imports DocumentFormat.OpenXml.Wordprocessing
    Class Foo
        Public Sub Create()
		Dim wordDocPath As String = Directory.GetCurrentDirectory & "\SampleDoc2.docx"
		Dim type as Object = DocumentFormat.OpenXml.WordProcessingDocumentType.Document
        ' I had to declare "type" and then use it below.
        ' Just using "WordProcessingDocument.Create(wordDocPath, WordProcessingDocumentType.Document
        ' threw an error
        Using myDocument As WordprocessingDocument = WordprocessingDocument.Create(wordDocPath, type)
            ' Add a main part. 
            Dim mainPart As MainDocumentPart = myDocument.AddMainDocumentPart()

            ' Create the document structure.
            mainPart.Document = New Document()
            Dim body As Body = mainPart.Document.AppendChild(New Body())
            Dim para As Paragraph = body.AppendChild(New Paragraph())
            Dim run As Run = para.AppendChild(New Run())

            ' Add some text to the document.
            run.AppendChild(New Text("I created this with AHK and DocumentFormat.OpenXml."))
            Dim para2 As Paragraph = body.AppendChild(New Paragraph())
            Dim run2 As Run = para2.AppendChild(New Run())
			run2.AppendChild(New Text("It was like pulling teeth"))
            myDocument.MainDocumentPart.Document.Save()
        End Using
        End Sub
    End Class
)
asm := CLR_CompileVB(vb, "System.dll | System.IO.dll | DocumentFormat.OpenXml.dll ")
obj := CLR_CreateObject(asm, "Foo")
obj.Create()
Regards,
burque505

Return to “Tips and Tricks”

Who is online

Users browsing this forum: No registered users and 4 guests