Article author: Sanjay Kumar Madhva, Sonata Software Limited
The idea of this article is to show how easy it is to create an OpenXML WordprocessingML using .NET and using System.IO.Packaging provided by WinFx.
What we need, is to create a windows application that lets user enter multi line of text. The user is provided a button that on click creates a WordprocessingML. When the user clicks on the button all we need to code for, breaking the user entered text into paragraphs and creating an document.xml as shown below. Package it into an OpenXML document.
Here are twelve easy steps to create a word processing document like the one above and write it out as a valid Open XML document ...
Create a new project “WordDocCreator” in a new solution.
Right click on the reference and form the pop up menu select “Add Reference”
Add reference windows pops up. Select “Windows Base” from the .NET tab as shown in the fig below.
Drag and drop TextBox from the ToolBox on to the form.
Change the textbox property to accept multiline.
Resize the textbox to fit to the screen.
Double click on the exit button to generate the click event for the button add close() in the button clicked event as shown below.
private void Exit_Click(object sender, EventArgs e){close();}
using System.Xml;using System.IO;using System.IO.Packaging;
We may have to create a file dialog that will accept a filename from the user. We can call the SaveFileDialog provided by the .net framework to get the directory and the name of the file in which the user wants to save the document content.
The code is as follows.
//Get the file path where the user wants to save the document.private string GetSavePath(){SaveFileDialog sfd = new SaveFileDialog();sfd.AddExtension = true;//Get only Docx filesfd.Filter = "docx|";sfd.CheckPathExists = true;sfd.DefaultExt = ".docx";sfd.ShowDialog();return sfd.FileName; // return the filename and the path}
The document creation can be achieved by following 5 easy steps:1. Take the text entered by the user in the multilane edit has to be split into paragraph and creating an “document.xml” as shown under “Content of document.xml”.2. Creating an instance of Package class3. Create the main document part (document.xml) using the package class.4. Create the relationship file.5. Close the document.
private void GenerateDocument_Click(object sender, EventArgs e){string _nameSpaceURI = "http://schemas.microsoft.com/office/word/2005/10/wordml";string docFileName = GetSavePath();//-- Step 1 - Creating the document xmlXmlDocument doc = new XmlDocument();XmlElement _wWordDoc = doc.CreateElement("w:wordDocument", _nameSpaceURI);doc.AppendChild (_wWordDoc);XmlElement _wbody = doc.CreateElement("w:body",_nameSpaceURI);_wWordDoc.AppendChild(_wbody);// Check if the string contains a line feedstring[] _SplitStr = mleTextForDocument.Text.Split('\n');// if it contains line feed then each entry with a line feed goes to a new paragraph.for (int row = 0; row < _SplitStr.Length; row++){XmlElement _wp1 = doc.CreateElement("w:p",_nameSpaceURI);_wbody.AppendChild(_wp1);XmlElement _wr1 = doc.CreateElement("w:r", _nameSpaceURI);_wp1.AppendChild(_wr1);XmlElement _wt11 = doc.CreateElement("w:t", _nameSpaceURI);_wr1.AppendChild(_wt11);XmlNode _wt1 = doc.CreateNode(XmlNodeType.Text, "w:t",_nameSpaceURI);_wt1.Value = _SplitStr[row];_wt11.AppendChild(_wt1);}//-- Step 2 - Creating the PackagePackage package = null;package = Package.Open(docFileName, FileMode.Create, FileAccess.ReadWrite);//-- Step 3 - Create the main document part (document.xml)Uri uri = new Uri("/word/document.xml", UriKind.Relative);PackagePart part = package.CreatePart(uri, "application/vnd.ms-word.main+xml");StreamWriter partWrt = new StreamWriter(part.GetStream(FileMode.Create, FileAccess.Write));doc.Save(partWrt);partWrt.Close();package.Flush();//-- Step 4 - Create the relationship fileuri = new Uri("/word/document.xml", UriKind.Relative);PackageRelationship rel = package.CreateRelationship(uri, TargetMode.Internal, "http://schemas.microsoft.com/office/2006/relationships/officeDocument", "rId1");package.Flush();//-- Step 5- Close the document.package.Close();}
From the Build menu select “Build WordDocument”
To run with out debug, select “Start Without Debugging” under “Debug” menu or press Ctrl+F5.
Application window appears.
Key in some text and click on “Generate Document” button, a file dialog appears. Provide the file name and click save.
Note: remember the save in directory.
Open file explorer and go the above-specified directory. Double click on the document you just created.
See the content you typed being displayed as a document ...