Val's Blog
Lots of stuff for Web 2.0 freaks and Java addicts
Feeds RSS | Atom | RDF
 
 
Jane Cleland-Huang: "Software development should integrate and consider project metrics that assess its financial impact."
[ Login ]

October 2004
SunMonTueWedThuFriSat
      1  2 
 3  4  5  6  7  8  9 
 10  11  12  13  14  15  16 
 17  18  19  20  21  22  23 
 24  25  26  27  28  29  30 
 31       
Sep  |  Today  |  Nov
XML Feeds   Subscribe with Bloglines

Javaranch Sheriff   My LinkedIn Profile
Drop me a line or two   Bloglines Blogroll
JavaRSS   Referers
How cool are you?   My Reviews

Next trips...
JavaOne 2008 (May 6-9, 08)
SpringOne 2008 (Jun 11-12, 08)
Ajax Exp. 2008 (Sep 29-Oct 1, 08)
Top 10 entries (#hits)
(As of Nov 30, 2007)


Top 10 entries (#hits/day)
Come Back (5.032)
(As of Nov 30, 2007)
Recent Blog Entries
Recent Blog Comments
Re: Review of "Marketing Management 12th"
i know marketing management by kotler is good book but the problem is that the management part of this book is totally missing as fare as i know managemet is complete different subject and it should not be mixed i am student of MBA i was looking at ass...

Re: Review of "Pro Spring"
Using simple POJOs + factories without Spring for "echo" and "counter" would be a lot more easier. No need to write those XML files... So, in this case using Spring makes me write a lot more code... (OK, you can generate everything with the help of And...

pls urgent
Hi I am trying to generate the word doc but i m not understanding wats happening any one pls figure it out /* * WordAPI.java * * Created on May 30, 2006, 10:50 AM * * To change this template, choose Tools | Template Manager * and open the te...
Archives (# entries)
Links
Other Blogs
Other Blogs

Reviewing
Reading
Locations of visitors to this page
What they once said...
 

Ever needed to generate Word documents from your Java applications? There are only a few tools that allow you to do that. The Apache POI team has developed an API for manipulating Excel files (org.apache.poi.hssf packages) and is currently developing one for Word files also (org.apache.poi.hwpf packages). However, the latter is still in early beta stages and is not bundled with the 2.0 release, so you have to go into CVS and get the files by yourself.

If this suffices, then you are good to go. Otherwise I can propose another solution. A German software company, called Müller & Stein Software, proposes on its website a free component (yes, as in "free" beer) that you can call directly from your Java application to generate any kind of Word files. The downside is that it won't let you read the Word file, though. You're gonna have to use the POI HWPF API if you need that functionality.

The way the whole thing works is incredibly easy. In the bundle, you will find three key files:

  • WordAPI.exe: Word driver component (2000/97) for any Windows platform (XP/2000/NT/ME/98/95)
  • WordProcessing.java: Main class to use from your Java applications to interact with the Word driver
  • SampleTemplate.dot: A template Word file with which you will customize the generation

All you have to do is to define bookmarks (Insert/Bookmark) in the template Word file and give them a name. This name will let you identify what goes where when you generate the Word file. Then, from you Java application, you can write code like:


1. WordProcessing.createNewDocumentFromTemplate("SampleTemplate");
2. WordProcessing.typeTextAtBookmark("AddressLine1", "O'Reilly & Associated, Inc.");
3. WordProcessing.typeTextAtBookmark("AddressLine2", "Mr Miller");
4. WordProcessing.typeTextAtBookmark("AddressLine3", "101 Moris Street");
5. WordProcessing.typeTextAtBookmark("AddressLine4", "Sebastopol, CA 95472-9902");
6. WordProcessing.typeTextAtBookmark("Salutation", "Dear Mr Miller,");
7. WordProcessing.exec();

Let me explain a little further what this code does:

  • On line 1, we let the driver create a new Word document by giving it a hardcoded template file name (without the extension!). There is another alternative in which you can let the user dynamically choose the template to use. Just use the method createNewDocumentFromTemplateToSelectByUser() instead
  • Lines 2 through 6 use the typeTextAtbookmark() method to send strings (2nd argument) to the given bookmark (1st argument). It is also possible to directly send an array of String objects in one shot instead of having to repeatedly call the typeTextAtbookmark() method.
  • Finally, you just invoke the exec() method to generate the Word file. Actually, until you call exec(), all the WordProcessing call does is to write commands into a temporary file that the Word driver will use.

Before calling exec(), you have the choice to call a variety of other methods as described below:

  • saveDocumentAs(): tells the driver under which name to save the generated Word document
  • closeDocument(): tells the driver to close the generated Word document
  • printAndForget(): tells the driver to print the generated Word document to the default printer. An overloaded method allows the developer to hardcode the name of the printer to print to. The file is not saved anywhere!
  • printToPrinterToSelectByUserAndForget(): pops up the printer dialog and tells the driver to print the generated Word document to the chosen printer. The file is not saved anywhere!
  • executeMacro(): tells the driver to run the macro whose name is given in argument.

As you can see this Java2Word component is very simple, yet very powerful. Play around with it and you won't be disappointed. The installation is straightforward and the driver is very fast. In my case, I have to generate 50 pages Word files, and the whole thing takes like four to five seconds.


Another approach is to use JooTemplates to create an OpenOffice.org file. From there, JooConverter can get you to Word, or PDF, or a few other formats. Not as easy, but completely open source, for places where that's important.
Thank you for your input. I will look into that solution as well :)
Hi, I am able to generate word document with WordApi.exe. But is it possible to insert image, page-break with this. I need to publish variable no of pages. Is it possible to repeat some "Section" ? Pls reply soon.
Hi,
I was trying the sample to generate the word document the same SampleTemplate.dot, that I downloaded and I wrote my own Java Class as follows

import de.must.util.WordProcessing;
public class WriteToDoc
{
public static void main(String args[])
{
WordProcessing.createNewDocumentFromTemplate("SampleTemplate");
WordProcessing.typeTextAtBookmark("AddressLine1", "O'Reilly & Associated, Inc.");
WordProcessing.typeTextAtBookmark("AddressLine2", "Mr Miller");
WordProcessing.typeTextAtBookmark("AddressLine3", "101 Moris Street");
WordProcessing.typeTextAtBookmark("AddressLine4", "Sebastopol, CA 95472-9902");
WordProcessing.typeTextAtBookmark("Salutation", "Dear Mr Miller,");
WordProcessing.exec();
}
}
and I kept the de.must.util.WordProcessing class file in the class path and compiled successfully.
But I am getting an error at runtime as follows

A window with title Protocol of Word Processing Control is getting opened and in that window
error msg is displayed as "Template SampleTemplate not found"

I kept the Sample Template.dot file in the same directory as WriteToDoc.class file is placed.

Please let me know the solution for this. thanks, Pramod.
Hello Pramod , 1).Is it possible to see the generated document in MS Word ? I got some info that its a bit complicated process to open the generated word doc in MS Word , using this api. 2) Also , are the images being rendered properly. Please respond man , its kinda urgent Regards, Aash K. aashish_kohli@satyam.com
Hi,

I got it working by placing the SampleTemplate.dot file in the default Templates directory

..Documents and Settings\Administrator\Application Data\Microsoft\Templates

Copied the SampleTemplate.dot file to above folder and got the Word Document created..

Thanks for API,
Pramod.
Hi pramod , I have downloaded this api[mull-und-stein] , but while i'm tyring to install WordApi.exe , i'm getting an error ... It says ..."The input file 'WordInp.txt' couldnot be found" Please tell how did you installed this api , and also the compiling instructions.
Here's an even better way to do this, and doesn't require Windoze to run the exe; http://blogs.msdn.com/dotnetinterop/archive/2005/03/29/403331.aspx
I am New to java.I have got a similar problem. the error is something like this Pls help me out. writetodoc.java:7: cannot resolve symbol symbol : variable WordProcessing location: class WriteToDoc WordProcessing.createNewDocumentFromTemplate("SampleTemplate"); ^ writetodoc.java:8: cannot resolve symbol symbol : variable WordProcessing location: class WriteToDoc WordProcessing.typeTextAtBookmark("AddressLine1", "O'Reilly & Associated, Inc." ; ^ writetodoc.java:9: cannot resolve symbol symbol : variable WordProcessing location: class WriteToDoc WordProcessing.typeTextAtBookmark("AddressLine2", "Mr Miller"); ^ writetodoc.java:10: cannot resolve symbol symbol : variable WordProcessing location: class WriteToDoc WordProcessing.typeTextAtBookmark("AddressLine3", "101 Moris Street"); ^ writetodoc.java:11: cannot resolve symbol symbol : variable WordProcessing location: class WriteToDoc WordProcessing.typeTextAtBookmark("AddressLine4", "Sebastopol, CA 95472-9902"); ^ writetodoc.java:12: cannot resolve symbol symbol : variable WordProcessing location: class WriteToDoc WordProcessing.typeTextAtBookmark("Salutation", "Dear Mr Miller,"); ^ writetodoc.java:13: cannot resolve symbol symbol : variable WordProcessing location: class WriteToDoc WordProcessing.exec(); ^
¡¡Puta madre no encuentro el driver HWPF!!

You can specify the Template file and WordAPI.exe are located but you cannot modify the directory location of the WordInp.txt. unless you compile WordAPI.exe yourself

You can implictly specify where the Word Template can be loaded from by specifying its location by passing the path+filename:


Example:
wp.createNewDocumentFromTemplate("C:\\SomeDirectory\\DifferentTemplate.dot");

You can implictly specify where to call the WordAPI.exe by specifying its location by passing the path+filename to:


Example
String[] cmd = {"C:\\SomeDirectory\\WordAPI.exe"}; ... Runtime.getRuntime().exec(cmd);

If you change the location of the WordInp.txt you will get the "The input file 'WordInp.txt'" error.


Please ensure that File is instantiated this way
wordInput = new File("WordInp.txt");
I'm new in java programming.I following above. I've already three key files (WordAPI.exe,WordProcessing.java andSampleTemplate.dot)and also follow in WriteToDoc.java(Pramod) but when I compile, program said WriteToDoc.java:1: package de.must.util does not exist import de.must.util.WordProcessing; ^ how can i solve this problem? please help me.
What is the file "WordInput.txt" for?? Where do I get one? I don't understand what it's for, because I've never seen such a file.
Hello I need Help. Everything seems to work fine, no error messages form the application - but it doesn't create any word files, it doesn't print anything. After execute the programm ends, and thats it. What is wrong? I was watching the Task Manager. WINWORD.EXE is started, after exec it uses 99% of CPU power for a 2 - 3 seconds, then nothing happens. winword.exe never ends. When I execute the programm again I get 2 WINWORD.EXE at tha Task Manager..then 3, 4... nothing else What is wrong? I'm using the example code from above.
With this API I can write a "table" of variable number of collumns and rows? There is any API to do this?
Any news on this?....
I want to generate a word document from dynamic data.Please help
doesnt seem that this API will help us in creating a table in the output word document? does it? any other ideas?
Hello I want to mention that it works now on my system. I used Windows 2000 and Office 97 and it didn't work. Now I upgradet to Office 2003 and it works. (Müller and Stein's page says it should work with Word 97, but it didn't)
how webpage converted to word document for print
Bado did you find any other solution where you could generate word document irrespective of Word 97 or latest?? Thanks
A better way to do this may be to use the WordProcessingML schema, and just generate XML. No special libs required. click here for an example
It is working fine. I would like to summarize how it worked out. 1. Downloaded source - Tried to install wordapi.exe. It throwed some error. Dont mind about that. 2. Compile WordProcessing.java 3. Store all the three key files in the same directory. 4. Create another java file with the source code given. 5. If the template file is stored in same directory then pass the whole path along with the createNewDocumentFromTemplate("c:\...") method or store it in default template directory. 6. Compile and run.... Doc created :)
I am calling this from a JSP on an ORION server, how do I specify that the word file be saved locally?
Hi, I have downloaded all 3 mentioned files...what r the locations to place them...procedures to follow then???
Hi, Is there a way to generate WordDocs using Java from a Unix Server running on SunOS. Is there a way to use templates too for the word docs creation. Regards, Ashish Kumar
I am able to Generate the Word Documemt. But when i use "closeDocument()" or "quitAppliation()" only the generated Document is getting closed not the Word Application. Every time i generate the document a new Word Application is opened which is never closed. How do I close the Application. Thanks in Advance
"I am able to Generate the Word Documemt. But when i use "closeDocument()" or "quitAppliation()" only the generated Document is getting closed not the Word Application. Every time i generate the document a new Word Application is opened which is never closed. How do I close the Application. " Is there a solution regarding this? thanks Nicolás Fonnegra
I'm taking an old report document and making a template from it. I am able to create bookmarks and use the files to write to them, unless one is in a Word textbox. Is there a way to reference a bookmark inside a textbox?
On another note is there someplace I can see what methods are inside the WordAPI.exe? As this is open source, if I can see the methods inside I could possibly write a java method to utilize one (assuming there is something in there to add text inside a textbox thanks
Hi all, I want to use this API but I cannot understand if I have to install the "WordAPI.exe" BEFORE using WordProcessing.java. Can anybody explain how to: 1. Install the API 2. Reference user tempates 3. Create Docs whit bookmarks filled The problem is that if I simply double-click on WordAPI.exe I have the usual problem related to WordInput.txt (file not found). What is this file??? Where is it? Thanx a lot, Marco
Hello, I have exactly the same problem whith this "WordInput.txt". Please, help us...
How to do the same thing over HTTP. I want to do the same process in the client side using some server side application. Please help.
hi, i'd like to write a word document making a mailing, ie. merging content of a document model with txt file containing fields values. An other question is to know if there is a word property for the txt file path and if we can modify it in the word file. thanx
Hi all, i want to make a merging between a word model document and a field values txt file using java. Other thing, is it possible to write word property about the path of the txt file any ideas thanx
Hello, Can I force it to create and open the documents on the client machines (online users accessing the application)?
I have similar kind of problem, I have to open a word document in read only format, which is located in unix Operating System(different location), my java applications runs on WinX. Can anybody throw any light on it, it would be helpful if any body send a sample code.........
i have a question. can I use the same thing using JBOSS, I want to create a report in word and show it in the browser. how can I do that? thanx
I am having similar a problem to the problem Bodo had in March. I get no errors, I see WordAPI.exe and WinWord.exe start in the Task Manager, but a document is never produced. I have tried to use the "printToPrinterToSelectByUserAndForget" method and the printer select dialog does not appear. I am calling the class from within JavaScript in another application. I think this class would really solve some problems for us, anyone have some suggestions?
Hi, WordAPI.exe, looks like it will work only on Windows.I have a requirement to create a word document within a UNIX enviornment.The file is later fed to Microsoft Windows, but before that, it has to be created within Unix. Can anybody help please?
Where can I get the following WordAPI.exe WordProcessing.java SampleTemplate.dot Can you forward the same to my email id so that I can make use of the api .
Hi, I'm going to migrate my Weblogic 7.0 J2EE application into JBoss. JCom doesn't come with JBoss and I'm thinking in using the proposed in this forum but I really don't know how to go about it. I have a Unix server for the Web application and a COM server where I save my word douments. Does anybody have an example of implementation? Kind Regards
I forgot to say that my templates have pictures and the tags are like «n» where n is a natural Thanks in advance
can u suggest me a logic to access a word application using java code. It will be very much helpfull if source code is provided.
i doin a project to make file browser in java.ll u plz guide me how to open a word file?
I am running a program that would make use of the created word document.. I need to know a way to wait, till the time the word document has been created successfully.. Is there an api that helps in this.
Please anybody upload working example? It will be appreciated.
iam using tomcat server,& need to generate word document at clientside.i can create the word doc wen the oath of wordapi is hardcoded like String cmd = "C:\\Tomcat 4.1\\webapps\\ajax1\\WEB-INF\\WordAPI.exe"; but how to access the wordApi.exe file from client machine. doe any body know how to do this Thank U
You would be best to create the document server side and stream it to the client once it is created, that way the api etc only need to live in the server classpath and not the client's one. the only assumption then being that the user has MSWord on their client. Else you will find massive portability problems. Hope this hel, S
I can read word document using jakarta POI API's. But i want to search and replace some of text in that document. How to modify same Word documents using jakarta POI??
I can read word document using org.apache.poi.hwpf.HWPFDocument class i get whole of text but i want to replace some text how can i do that?? if u know abt this plx let me know... Thanks in advance
Hi, I am able to generate word document with WordApi.exe. But I try to created word document with header WordProcessing.typeTextAtBookmark("AddressLine1", "My header") and get Bookmark AddressLine1 in template not found. Dose anyone have idea? Help!
Hi I am trying to generate the word doc but i m not understanding wats happening any one pls figure it out /* * WordAPI.java * * Created on May 30, 2006, 10:50 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package com.arbitron.specialnoticespage; import java.io.IOException; /** * * @author rsoni */ public class WordAPI { /** Creates a new instance of WordAPI */ public WordAPI(String output, String Survey, String Market, String Year, String[] cmdMacro, String[] dataWord) { String cmd = "C:\\DocumentsandSettings\\elthot\\Desktop\\BackUp\\JavaWord\\WordAPI.exe"; WordProcessing.createNewDocumentFromTemplate("C:\\Documents and Settings\\elthot\\Desktop\\BackUp\\Project #6-SSA\\SpecialPlate.dot"); ///////////////////// WordProcessing.executeMacro("InitializeForm"); WordProcessing.typeTextAtBookmark("Survey", Survey); WordProcessing.typeTextAtBookmark("Market", Market); WordProcessing.typeTextAtBookmark("Year", Year); WordProcessing.executeMacro("InitializeFormData"); for(int x=0; x<cmdMacro.length; x++){ WordProcessing.executeMacro(cmdMacro[x]); } int SectionCount=1; int SubtitleCount=1; int NoticeCount=1; int TableHeaderCount=1; int TableValueCount=1; int RowCount=1; int ColumnCount=1; int y=0; for(int x=0; x<dataWord.length; x++){ if(cmdMacro[y].compareTo("SectionHead")==0){ WordProcessing.typeTextAtBookmark("Section"+String.valueOf(SectionCount), dataWord[x]); /////////////////////////////////////////// System.out.println("Section"+String.valueOf(SectionCount)+" "+dataWord[x]); /////////////////////////////////////////// SectionCount++; } else if(cmdMacro[y].compareTo("SubTitle")==0){ WordProcessing.typeTextAtBookmark("Subtitle"+String.valueOf(SubtitleCount), dataWord[x]); /////////////////////////////////////////// System.out.println("Subtitle"+String.valueOf(SubtitleCount)+" "+dataWord[x]); /////////////////////////////////////////// SubtitleCount++; } else if(cmdMacro[y].compareTo("Notice")==0){ WordProcessing.typeTextAtBookmark("Notice"+String.valueOf(NoticeCount), dataWord[x]); /////////////////////////////////////////// System.out.println("Notice"+String.valueOf(NoticeCount)+" "+dataWord[x]); /////////////////////////////////////////// NoticeCount++; } else if(cmdMacro[y].compareTo("ResetTable")==0){ RowCount=1; ColumnCount=1; y++; while(cmdMacro[y].compareTo("AddRow")==0){ RowCount++; y++; } while(cmdMacro[y].compareTo("AddColumn")==0){ ColumnCount++; y++; } if((cmdMacro[y].compareTo("Table_Border")==0)||(cmdMacro[y].compareTo("Table_NoBorder")==0)){ for(int i=0; i<ColumnCount; i++){ WordProcessing.typeTextAtBookmark("TableHeader"+String.valueOf(TableHeaderCount), dataWord[x]); ////////////////////////////////////////////////////// // System.out.println("TableHeader"+String.valueOf(TableHeaderCount)+" "+dataWord[x]); ////////////////////////////////////////////////////// TableHeaderCount++; x++; } for(int i=0; i<(ColumnCount*RowCount-ColumnCount); i++){ WordProcessing.typeTextAtBookmark("TableValue"+String.valueOf(TableValueCount), dataWord[x]); /////////////////////////////////////////////////////// // System.out.println("TableValue"+String.valueOf(TableValueCount)+" "+dataWord[x]); /////////////////////////////////////////////////////// TableValueCount++; x++; } x--; } } else if(cmdMacro[y].compareTo("BackSpace")==0){ x--; } y++; } WordProcessing.saveDocumentAs(output); WordProcessing.exec(cmd); // try { // Runtime.getRuntime().exec(cmd); // } catch (IOException ex) { // ex.printStackTrace(); // } } }


Add a comment

Title
Body
HTML : b, i, blockquote, br, p, pre, a href="", ul, ol, li
Math Quiz 6 + 6 = (Helps stop blog spam)
Name
E-mail address
Website
Remember me Yes  No 

E-mail addresses are not publicly displayed, so please only leave your e-mail address if you would like to be notified when new comments are added to this blog entry (you can opt-out later).

TrackBack to http://radio.javaranch.com/val/addTrackBack.action?entry=1097909528000

 
About this Blog