The other day I had a need to create many word documents in code and publish them
up to a SharePoint 2010 site.
1 static void Main(string[] args) 2 { 3 int iMAXDocs = 200; 4 string fpath = Path.Combine(Directory.GetCurrentDirectory(), "Docs"); 5 Directory.CreateDirectory(fpath); 6 Console.WriteLine("Path created"); 7 for (int i = 0; i < iMAXDocs; i++) 8 { 9 string docname = Path.Combine(fpath, "Doc" + i.ToString() + ".docx"); 10 CreateWordDoc(docname); 11 Console.WriteLine("Created Doc {0} of {1}", i, iMAXDocs); 12 } 13 14 }
So essentially it went something like thatwith the key really being line#10 – CreateWordDoc().
The CreateWordDoc routine also adds a couple of custom String properties to the document.
1 private static void CreateWordDoc(string docname) 2 { 3 using (WordprocessingDocument package = 4 WordprocessingDocument.Create(docname, WordprocessingDocumentType.Document)) 5 { 6 // Add a new main document part. 7 package.AddMainDocumentPart(); 8 9 // Create the Document DOM - which could be from a template XML file or so. 10 package.MainDocumentPart.Document = 11 new Document( 12 new Body( 13 new Paragraph( 14 new Run( 15 new Text("Hello World!"))))); 16 17 //add props. 18 CustomFilePropertiesPart pt = package.CustomFilePropertiesPart; 19 if (pt==null) 20 pt = package.AddCustomFilePropertiesPart(); 21 22 XmlDocument xdoc = new XmlDocument(); 23 xdoc.LoadXml("<Properties xmlns='http://schemas.openxmlformats.org/officeDocument/2006/custom-properties' " 24 + "xmlns:vt='http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'>" 25 + "<property fmtid='{D5CDD505-2E9C-101B-9397-08002B2CF9AE}' pid='2' name='temp'> " 26 + "<vt:lpwstr>Done in Open XML</vt:lpwstr>" 27 + "</property>" 28 + "<property fmtid='{D5CDD505-2E9C-101B-9397-08002B2CF9AE}' pid='3' name='micksdemo'>" 29 + "<vt:lpwstr>SharePoint is Cool</vt:lpwstr>" 30 + "</property>" 31 + "</Properties>"); 32 33 //save the props 34 xdoc.Save(pt.GetStream()); 35 36 // Save changes to the main document part. 37 package.MainDocumentPart.Document.Save(); 38 39 } 40 }
>
All in all pretty straight forward using OpenXML Format SDK 2.0
Here’s the VS.NET2010 Solution of the above code –
WordDocCreator