3 people like it.

Create Open XML Word document

Create Open XML Word document using the open XML SDK

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
//reference to the Open Office SDK
#r @"C:\Program Files (x86)\Open XML SDK\V2.0\lib\DocumentFormat.OpenXml.dll"
//reference to the package 
#r "WindowsBase"

open DocumentFormat.OpenXml;
open DocumentFormat.OpenXml.Wordprocessing
open DocumentFormat.OpenXml.Packaging

let testString = "This is a test"
let printXml text =
    printfn "xml: %s" text

let createBody (text:string) =
    let text = new Text(text)
    let run = new Run()
    run.AppendChild(text) |> ignore
    let para = new Paragraph()
    para.AppendChild(run)|> ignore
    let body = new Body()
    body.AppendChild(para)|> ignore
    body

printXml (createBody testString).InnerXml

let createDocument (text:string) =
   let body = createBody text
   let doc = new Document()
   doc.AppendChild(body) |> ignore
   doc

printXml (createDocument testString).InnerXml

let createWordprocessingDocument (filepath:string) text=
    using (WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) (fun doc ->
    let mainPart = doc.AddMainDocumentPart();
    mainPart.Document <- createDocument text 
    )

let result3 = createWordprocessingDocument @"D:\Tmp\test1.docx" testString
val testString : string

Full name: Script.testString
val printXml : text:string -> unit

Full name: Script.printXml
val text : string
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val createBody : text:string -> 'a

Full name: Script.createBody
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
val text : obj
val run : obj
val ignore : value:'T -> unit

Full name: Microsoft.FSharp.Core.Operators.ignore
val para : obj
val body : 'a
val createDocument : text:string -> 'a

Full name: Script.createDocument
val body : obj
val doc : 'a
val createWordprocessingDocument : filepath:string -> text:'a -> 'b

Full name: Script.createWordprocessingDocument
val filepath : string
val text : 'a
val using : resource:'T -> action:('T -> 'U) -> 'U (requires 'T :> System.IDisposable)

Full name: Microsoft.FSharp.Core.Operators.using
val doc : System.IDisposable
val mainPart : obj
val result3 : obj

Full name: Script.result3
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/53
Posted:13 years ago
Author:Piet Amersfoort
Tags: open xml , word