http://openxmldeveloper.org/articles/OpenXMLDocFromDotNet.aspx
Article author: Sanjay Kumar Madhva, Sonata Software Limited
Introduction
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.
Content of document.xml
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 …
Step 1. Create a new C# project.
Create a new project “WordDocCreator” in a new solution.

Step 2. Add reference to WindowsBase provided WinFx.
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.

Step 3. Add a Text box to the form
Drag and drop TextBox from the ToolBox on to the form.

Step 4. Change the textbox to accept MultiLine.
Change the textbox property to accept multiline.

Step 5. Resize the textbox
Resize the textbox to fit to the screen.

Step 6. Add two Buttons.

Step 7. Rename the text box, and the two buttons.
- Change the forms title text to Document Creator
- Rename the Text box to mleTextForDocument
- Command button 1 to Exit and change the text to “E&xit”
- Command button 2 to GenerateDocument and change the text to “&Generate Document”

Step 8. Code for close event of Exit button
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();
}
Step 9. Add using directive
using System.Xml;
using System.IO;
using System.IO.Packaging;
Step 10. Create a method to get the save file name and path.
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 file
sfd.Filter = “docx|”;
sfd.CheckPathExists = true;
sfd.DefaultExt = “.docx”;
sfd.ShowDialog();
return sfd.FileName; // return the filename and the path
}
Step 11. Code for close event of GenerateDocument button
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 class
3. 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 xml
XmlDocument 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 feed
string[] _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 Package
Package 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 file
uri = 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();
}
Step 12. Build and Run.
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 …

Comments
jkemmery said:
planks said:
I also sent the output to be displayed in the console and it is doing it as it should so I think there’s something about file writing permissions, any ideas?
SanjayKumarM said:
1.
Seach for->
http://schemas.microsoft.com/office/word/2005/10/wordml
replace with->
http://schemas.openxmlformats.org/wordprocessingml/2006/3/main
2.
Seach for-> application/vnd.ms-word.main+xml
replace with->
application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml
3.
Seach for->
http://schemas.microsoft.com/office/2006/relationships/officeDocument
replace with->
http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument
SanjayKumarM said:
The code was written for Office 2007 Beta1, I have also posted the changes to be made to make it workable for Beta 2.
I have really tested the code it works, May be the version of WinFx or office 12 you are using may mot be the corrent one.
If you want I can email the code to you.
Sanjay
radwagner said:
I’m pleased to see your example as this is exactly what I’m looking for. However, when I open the document created by the sample in Office 12 Beta 2, I get “Elements and Attributes in restricted namespaces are not allowed”. Location: Part: /word/document.xml Line: 2, Column: 89. Other samples I’ve tried as posted give the same details.
Thanks,
RW
ivofoi said:
“The Office Open XML file try.docx cannot be opened because there are problems with the contents.” and
“Microsoft Office cannot open this file because some parts are missing or invalid.”.
Can anyone help me with this problem?
thx
ivofoi said: