1 people like it.

Create a Open Xml word document from a string array

Create a Open Xml word document from a string array. In this snippet I did not reference 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: 
41: 
42: 
43: 
44: 
45: 
46: 
47: 
48: 
49: 
50: 
51: 
52: 
53: 
54: 
55: 
56: 
57: 
58: 
59: 
60: 
61: 
62: 
63: 
64: 
65: 
66: 
67: 
68: 
69: 
70: 
71: 
//reference to the package 
#r "WindowsBase"
//reference to the Xml and Linq 
#r "System.Xml"
#r "System.Xml.Linq"

open System
open System.IO
open System.IO.Packaging
open System.Xml
open System.Xml.Linq

//helpers to create XName with a namespace and namespace
let xname str =
    XName.Get(str, "http://schemas.openxmlformats.org/wordprocessingml/2006/main")

let ns = XNamespace.Get("http://schemas.openxmlformats.org/wordprocessingml/2006/main")

//create the xml from the text (string array)
let createDocument (text:string[]) = 
    //helper to create a paragraph from a string
    let createP (text:string) =
        let el = new XElement(xname "p",
                    new XElement(xname "r",
                        new XElement(xname "t", text)
                        ))
        el
    //the content of the document
    let createContent =
        let content = new XElement(xname "document",
                        new XAttribute(XNamespace.Xmlns + "w", ns))
        let body = new XElement(xname "body")
        let r = text |> Array.map createP
        body.Add(r)
        content.Add(body)
        content
    //add the content to the declartion
    let doc =new XDocument(new XDeclaration("1.0", "utf-8", "true"))
    let content = createContent
    doc.Add(content)
    doc

//add the document to package and save
let createFile (xDocument:XDocument) (fileName:string) =
    using (Package.Open(fileName, FileMode.Create, FileAccess.ReadWrite))(fun package ->
        let uri = new Uri("/word/document.xml", UriKind.Relative )
        let partDocumentXML = 
            package.CreatePart(
                                uri,
                                "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml" )
    
        using(new StreamWriter(partDocumentXML.GetStream(FileMode.Create, FileAccess.Write)))(fun stream ->
            xDocument.Save(stream)
        )

        package.CreateRelationship(
                                    uri,
                                    TargetMode.Internal,
                                    "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
                                    "rId1") |> ignore
    )


//test
let text = [|"test1"; "test2"; "test3"; "test4"|]

let document = createDocument text

let fileName = @"D:\Tmp\test.docx"

createFile document fileName;;
namespace System
namespace System.IO
namespace System.IO.Packaging
namespace System.Xml
namespace System.Xml.Linq
val xname : str:string -> XName

Full name: Script.xname
val str : string
type XName =
  member Equals : obj:obj -> bool
  member GetHashCode : unit -> int
  member LocalName : string
  member Namespace : XNamespace
  member NamespaceName : string
  member ToString : unit -> string
  static member Get : expandedName:string -> XName + 1 overload

Full name: System.Xml.Linq.XName
XName.Get(expandedName: string) : XName
XName.Get(localName: string, namespaceName: string) : XName
val ns : XNamespace

Full name: Script.ns
type XNamespace =
  member Equals : obj:obj -> bool
  member GetHashCode : unit -> int
  member GetName : localName:string -> XName
  member NamespaceName : string
  member ToString : unit -> string
  static member Get : namespaceName:string -> XNamespace
  static member None : XNamespace
  static member Xml : XNamespace
  static member Xmlns : XNamespace

Full name: System.Xml.Linq.XNamespace
XNamespace.Get(namespaceName: string) : XNamespace
val createDocument : text:string [] -> XDocument

Full name: Script.createDocument
val text : string []
Multiple items
val string : value:'T -> string

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

--------------------
type string = String

Full name: Microsoft.FSharp.Core.string
val createP : (string -> XElement)
val text : string
val el : XElement
Multiple items
type XElement =
  inherit XContainer
  new : name:XName -> XElement + 4 overloads
  member AncestorsAndSelf : unit -> IEnumerable<XElement> + 1 overload
  member Attribute : name:XName -> XAttribute
  member Attributes : unit -> IEnumerable<XAttribute> + 1 overload
  member DescendantNodesAndSelf : unit -> IEnumerable<XNode>
  member DescendantsAndSelf : unit -> IEnumerable<XElement> + 1 overload
  member FirstAttribute : XAttribute
  member GetDefaultNamespace : unit -> XNamespace
  member GetNamespaceOfPrefix : prefix:string -> XNamespace
  member GetPrefixOfNamespace : ns:XNamespace -> string
  ...

Full name: System.Xml.Linq.XElement

--------------------
XElement(name: XName) : unit
XElement(other: XElement) : unit
XElement(other: XStreamingElement) : unit
XElement(name: XName, content: obj) : unit
XElement(name: XName, [<ParamArray>] content: obj []) : unit
val createContent : XElement
val content : XElement
Multiple items
type XAttribute =
  inherit XObject
  new : other:XAttribute -> XAttribute + 1 overload
  member IsNamespaceDeclaration : bool
  member Name : XName
  member NextAttribute : XAttribute
  member NodeType : XmlNodeType
  member PreviousAttribute : XAttribute
  member Remove : unit -> unit
  member SetValue : value:obj -> unit
  member ToString : unit -> string
  member Value : string with get, set
  ...

Full name: System.Xml.Linq.XAttribute

--------------------
XAttribute(other: XAttribute) : unit
XAttribute(name: XName, value: obj) : unit
property XNamespace.Xmlns: XNamespace
val body : XElement
val r : XElement []
type Array =
  member Clone : unit -> obj
  member CopyTo : array:Array * index:int -> unit + 1 overload
  member GetEnumerator : unit -> IEnumerator
  member GetLength : dimension:int -> int
  member GetLongLength : dimension:int -> int64
  member GetLowerBound : dimension:int -> int
  member GetUpperBound : dimension:int -> int
  member GetValue : [<ParamArray>] indices:int[] -> obj + 7 overloads
  member Initialize : unit -> unit
  member IsFixedSize : bool
  ...

Full name: System.Array
val map : mapping:('T -> 'U) -> array:'T [] -> 'U []

Full name: Microsoft.FSharp.Collections.Array.map
XContainer.Add([<ParamArray>] content: obj []) : unit
XContainer.Add(content: obj) : unit
val doc : XDocument
Multiple items
type XDocument =
  inherit XContainer
  new : unit -> XDocument + 3 overloads
  member Declaration : XDeclaration with get, set
  member DocumentType : XDocumentType
  member NodeType : XmlNodeType
  member Root : XElement
  member Save : fileName:string -> unit + 6 overloads
  member WriteTo : writer:XmlWriter -> unit
  static member Load : uri:string -> XDocument + 7 overloads
  static member Parse : text:string -> XDocument + 1 overload

Full name: System.Xml.Linq.XDocument

--------------------
XDocument() : unit
XDocument([<ParamArray>] content: obj []) : unit
XDocument(other: XDocument) : unit
XDocument(declaration: XDeclaration, [<ParamArray>] content: obj []) : unit
Multiple items
type XDeclaration =
  new : other:XDeclaration -> XDeclaration + 1 overload
  member Encoding : string with get, set
  member Standalone : string with get, set
  member ToString : unit -> string
  member Version : string with get, set

Full name: System.Xml.Linq.XDeclaration

--------------------
XDeclaration(other: XDeclaration) : unit
XDeclaration(version: string, encoding: string, standalone: string) : unit
val createFile : xDocument:XDocument -> fileName:string -> unit

Full name: Script.createFile
val xDocument : XDocument
val fileName : string
val using : resource:'T -> action:('T -> 'U) -> 'U (requires 'T :> IDisposable)

Full name: Microsoft.FSharp.Core.Operators.using
type Package =
  member Close : unit -> unit
  member CreatePart : partUri:Uri * contentType:string -> PackagePart + 1 overload
  member CreateRelationship : targetUri:Uri * targetMode:TargetMode * relationshipType:string -> PackageRelationship + 1 overload
  member DeletePart : partUri:Uri -> unit
  member DeleteRelationship : id:string -> unit
  member FileOpenAccess : FileAccess
  member Flush : unit -> unit
  member GetPart : partUri:Uri -> PackagePart
  member GetParts : unit -> PackagePartCollection
  member GetRelationship : id:string -> PackageRelationship
  ...

Full name: System.IO.Packaging.Package
Package.Open(stream: Stream) : Package
Package.Open(path: string) : Package
Package.Open(stream: Stream, packageMode: FileMode) : Package
Package.Open(path: string, packageMode: FileMode) : Package
Package.Open(stream: Stream, packageMode: FileMode, packageAccess: FileAccess) : Package
Package.Open(path: string, packageMode: FileMode, packageAccess: FileAccess) : Package
Package.Open(path: string, packageMode: FileMode, packageAccess: FileAccess, packageShare: FileShare) : Package
type FileMode =
  | CreateNew = 1
  | Create = 2
  | Open = 3
  | OpenOrCreate = 4
  | Truncate = 5
  | Append = 6

Full name: System.IO.FileMode
field FileMode.Create = 2
type FileAccess =
  | Read = 1
  | Write = 2
  | ReadWrite = 3

Full name: System.IO.FileAccess
field FileAccess.ReadWrite = 3
val package : Package
val uri : Uri
Multiple items
type Uri =
  new : uriString:string -> Uri + 5 overloads
  member AbsolutePath : string
  member AbsoluteUri : string
  member Authority : string
  member DnsSafeHost : string
  member Equals : comparand:obj -> bool
  member Fragment : string
  member GetComponents : components:UriComponents * format:UriFormat -> string
  member GetHashCode : unit -> int
  member GetLeftPart : part:UriPartial -> string
  ...

Full name: System.Uri

--------------------
Uri(uriString: string) : unit
Uri(uriString: string, uriKind: UriKind) : unit
Uri(baseUri: Uri, relativeUri: string) : unit
Uri(baseUri: Uri, relativeUri: Uri) : unit
type UriKind =
  | RelativeOrAbsolute = 0
  | Absolute = 1
  | Relative = 2

Full name: System.UriKind
field UriKind.Relative = 2
val partDocumentXML : PackagePart
Package.CreatePart(partUri: Uri, contentType: string) : PackagePart
Package.CreatePart(partUri: Uri, contentType: string, compressionOption: CompressionOption) : PackagePart
Multiple items
type StreamWriter =
  inherit TextWriter
  new : stream:Stream -> StreamWriter + 6 overloads
  member AutoFlush : bool with get, set
  member BaseStream : Stream
  member Close : unit -> unit
  member Encoding : Encoding
  member Flush : unit -> unit
  member Write : value:char -> unit + 3 overloads
  static val Null : StreamWriter

Full name: System.IO.StreamWriter

--------------------
StreamWriter(stream: Stream) : unit
StreamWriter(path: string) : unit
StreamWriter(stream: Stream, encoding: Text.Encoding) : unit
StreamWriter(path: string, append: bool) : unit
StreamWriter(stream: Stream, encoding: Text.Encoding, bufferSize: int) : unit
StreamWriter(path: string, append: bool, encoding: Text.Encoding) : unit
StreamWriter(path: string, append: bool, encoding: Text.Encoding, bufferSize: int) : unit
PackagePart.GetStream() : Stream
PackagePart.GetStream(mode: FileMode) : Stream
PackagePart.GetStream(mode: FileMode, access: FileAccess) : Stream
field FileAccess.Write = 2
val stream : StreamWriter
XDocument.Save(writer: XmlWriter) : unit
XDocument.Save(textWriter: TextWriter) : unit
XDocument.Save(stream: Stream) : unit
XDocument.Save(fileName: string) : unit
XDocument.Save(textWriter: TextWriter, options: SaveOptions) : unit
XDocument.Save(stream: Stream, options: SaveOptions) : unit
XDocument.Save(fileName: string, options: SaveOptions) : unit
Package.CreateRelationship(targetUri: Uri, targetMode: TargetMode, relationshipType: string) : PackageRelationship
Package.CreateRelationship(targetUri: Uri, targetMode: TargetMode, relationshipType: string, id: string) : PackageRelationship
type TargetMode =
  | Internal = 0
  | External = 1

Full name: System.IO.Packaging.TargetMode
field TargetMode.Internal = 0
val ignore : value:'T -> unit

Full name: Microsoft.FSharp.Core.Operators.ignore
val text : string []

Full name: Script.text
val document : XDocument

Full name: Script.document
val fileName : string

Full name: Script.fileName

More information

Link:http://fssnip.net/5j
Posted:8 years ago
Author:Piet Amersfoort
Tags: open xml , word