Saturday, May 8, 2010

Open XML Hello World

Currently I am Involved In Open Xml project.. I was Hard to Find Some Good resource regarding OpenXml So I taught I Should Create My Own So I have..

Requirement (What I Have used):-

OpenXML SDK 2.0
Visual Studio 2008

Let Start:-

Add Some Assemblies

DocumentFormat.OpenXml
Window.Base
System.Xml
System.IO
System.IO.Packaging

Download OpenXMl SDK..



ADD
DocumentFormat.OpenXml

Window.Base
Assemblies




CODE WHAT I HAVE USED

Assemblies

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Packaging;
using System.IO;
using System.Xml;

Creating Package Method..

public void CreatePackage()
{
//File Would Create in D Drive With name Sample.docx
using (Package package = Package.Open("D://Sample.docx", FileMode.Create))
{

PackagePart mainPart = package.CreatePart(
new Uri("/Words/document.xml", UriKind.Relative),"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");

//This Method Which has Code Below
XMLFile(mainPart);


PackageRelationship mainRelationship = package.CreateRelationship(
mainPart.Uri,
TargetMode.Internal,
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument");


}

}
XMLFile METHOD


public void XMLFile(PackagePart mainPart)
{
string xmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
using (XmlWriter writer = XmlWriter.Create(mainPart.GetStream(FileMode.Create, FileAccess.ReadWrite)))
{
writer.WriteStartDocument();
writer.WriteStartElement("w", "document", xmlNamespace);
writer.WriteStartElement("w", "body", xmlNamespace);
writer.WriteStartElement("w", "p", xmlNamespace);
writer.WriteStartElement("w", "r", xmlNamespace);
writer.WriteStartElement("w", "t", xmlNamespace);
writer.WriteString("Hello World");
writer.WriteEndDocument();
}

}

OutPut Of Code


Opening Docx File In WinRar

Extraction DOCX file in Folder


Word folder Is Created Becuause be Defined In code

new Uri("/Words/document.xml", UriKind.Relative)

Now Going To Document.xml


Now Checking Document.xml


This is all about OpenXMl Hello World
Hope It Helps Some Body To Understand






No comments:

Post a Comment