Sunday, November 11, 2012

F# create Word document using OpenXML document

I always want to find a way to expose F# output to a nice UI and expose it directly to user. One of the nice UI is MS Word. I download OpenXML SDK from Microsoft and this helps me to write to Word and expose the result in very professional way. :)

I checked some online tutorial and found the C# always use Append to add new element. I converted C# code to F# and the generated document always shows nothing. After unzip the package, I should AppendChild. The following code is to use F# with OpenXML SDK to create a new Word document. I will explore more on this SDK next week.

 let createDoc(record) =   

   let name, content = record  
   let filePath = sprintf @".\%s.docx" name  
   let myDoc = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document)
  
   // Add a new main document part.   
   let mainPart = myDoc.AddMainDocumentPart()  

   //Create Document tree for simple document.   
   mainPart.Document <- Document()  

   //Create Body (this element contains other elements that we want to include  
   let body = Body()  

   //Create paragraph  
   let createParagraph(text) =   
     let paragraph = Paragraph()  
     let run_paragraph = Run()  
     // we want to put that text into the output document  
     let text_paragraph = Text text  
     //Append elements appropriately.  
     ignore <| run_paragraph.AppendChild(text_paragraph)  
     ignore <| paragraph.AppendChild(run_paragraph)  
     paragraph  

   //create a paragraph with text  
   let paragraph0 =   
       createParagraph   
         (sprintf "Dear %s" name)  
   let paragraph1 =   
       createParagraph   
         (sprintf "Congratulations! %s" content)  

   [paragraph0; paragraph1]  
   |> List.iter (body.AppendChild>>ignore)  
   ignore <| mainPart.Document.AppendChild(body)  

   // Save changes to the main document part.   
   mainPart.Document.Save()  
   myDoc.Close()  

No comments: