Thursday, April 9, 2009

Manipulating Microsoft Office 2007 with java - Creating "docx"

Hi All,

As we know that Microsoft Office suit 2007 is based on openXML formate. It is not so common how we can use it with Apache POI.


Apache POI is still very much exciting api used to manipulate Microsoft Office suit (<2007).>

I will post series of examples in my different posts, so that users could find easy to use openXML4J.

You can download the openxml4j from http://openxml4j.org/

Download all jar files and put into the classpath of your project.

Apart from that u also need to download and use "dom4j.jar"

Now I will give you one small example which will guide u how to create the Office 2007 "docx" file by using jaya


import java.io.File;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import org.openxml4j.opc.Package;
import org.openxml4j.opc.PackagePart;
import org.openxml4j.opc.PackagePartName;
import org.openxml4j.opc.PackageRelationshipTypes;
import org.openxml4j.opc.PackagingURIHelper;
import org.openxml4j.opc.StreamHelper;
import org.openxml4j.opc.TargetMode;

/**
* @author Anees
*
*/
public class CreatingSimpleDocument {

/**
* @param args
*/
public static void main(String[] args) {
try{
File outputDocument = new File("c:/icba10/simple.docx");
// Create package
Package pkg = Package.create(outputDocument);
// -------------------------------------- Creating parts -----------------------------
/*
* main part
*/
PackagePartName corePartName = PackagingURIHelper.createPartName("/word/document.xml");
// create main part relationship
pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT, "rId1");
// Create main document part
PackagePart corePart =
pkg.createPart(corePartName,
"application/vnd.openxmlformats- officedocument.wordprocessingml.document.main+xml");
// Create main document part contents
Document doc = DocumentHelper.createDocument();
Namespace nsWordprocessinML = new Namespace("w",
"http://schemas.openxmlformats.org/wordprocessingml/2006/main");
Element elDocument = doc.addElement(new QName("document",
nsWordprocessinML));
Element elBody = elDocument.addElement(new QName("body",
nsWordprocessinML));
Element elParagraph = elBody.addElement(new QName("p",
nsWordprocessinML));
Element elRun = elParagraph
.addElement(new QName("r", nsWordprocessinML));
Element elText = elRun.addElement(new QName("t", nsWordprocessinML));
elText.setText("Hello! This is Anees-ur-Rehman who wanna fly high.....!");

// Save the XML structure into the part
StreamHelper.saveXmlInStream(doc, corePart.getOutputStream());

// Save package
pkg.close();
}catch(Exception e){
e.printStackTrace();
}
}

}

This is the simple example which will give you the idea how to manipulate openxml.

Cheers

Anees

No comments: