Great things are tea-breaks; this one is giving me the chance to send some
code I put together before starting work today, but firstly the bad news.
The code that you will find below has been tested with versions 3.2FINAL,
3.5FINAL, 3.6 and 3.7 and it only works correctly with the first version -
3.2FINAL. If it is compiled and run against the later versions, the file
seems to grow when you open it with Word 2007. By 'grow' I mean that as the
file is read, Word seems to keep adding new pages to the document suggesting
that the file was not closed cuorrectly when it was created I guess. It is
quite a fascinating thing to see and will not do any damage to your machine
so give it a go. It would also be worthwhile seeing if the same problem
occurs when the 'faulty' file is opened with Word 2000 or 2003 say if you
have access to either of these versions. I am going to try with OpenOffice a
little later to see how it copes as that will help me to decide of the fault
is in the file that the pater version of HWPF creates or in the newer
versions of Word.
Anyway, it shows you the basic approach to creating a Word document using
HWPF. The first thing you will need to do is create a completly empty file
using Word as HWPF is not currently able to start from scratch to coin a
phrase. This process is very simple;
* Open Word.
* Click on New > Blank Document and then save the file away - I have called
mine Empty Doc.doc, Template.doc, etc in the past, it really does not
matter as long as you note where it was stored and what it's name is.
Next, you basically use HWPF to open the document and populate it with text.
The approach is quite straightforward and simply and relies upon the
insertAfter() method defined on the Range object - there is a method called
insertBefore() but I am assuming that you wish to build the document from
the top down as I tend to do and so the insertAfter() method is the better
one to use IMO. Put simply, the basic approach is this;
Add a Paragraph to the document.
Add CharacterRun(s) to the Paragraph and once that paragraph of text is
complete
Add a Paragraph to the document; the wrinkle being that you call the
insertAfter method on the last CharacterRun of the previous Paragraph.
etc, etc, etc.
Looking at the code in the newWordDoc() method below, you will see this
basic approach in a little more detail. After opening the Word template
document, the first step is to obtain the Range object that encapsulates the
contents of the document, thus;
Range range = doc.getRange();
Next, a new paragraph can be inserted into the document, thus;
Paragraph par1 = range.insertAfter(new ParagraphProperties(), 0);
ignore the next few lines and focus instead on this one;
CharacterRun run1 = par1.insertAfter("one");
It inserts text into the paragraph that was created above, in this case it
is just a single word but the later examples show how to add more text.
If you look at this line;
Paragraph par2 = run1.insertAfter(new ParagraphProperties(), 0);
you can see that you add a new Paragraph by inserting it after the previous
CharacterRun object not by trying to insert it after the previous Paragraph
as you might expect.
Next look down to the piece of code that begins with this line;
Paragraph par3 = run2.insertAfter(new ParagraphProperties(), 0);
What follows is an attempt - note that word, 'attempt' - to show how to
insert more than one sentence into a Paragraph and how to set the properties
of specific items of text within that Paragraph - for instance to italicise
part of the text only or to set a single word to be bold. As you can see,
there are a few lines commented out, lines like this one;
//run5.setItalic(false);
which is attempting to ensure that the text in CharacterRun run5 is not
italicised. Sadly, if you uncomment that line, compile and then run the
code, you will be confronted with an exception, an
IndexOutOfBoundsException. This is one of the larger problems still
remaining with HWPF, it is not possible to set or re-set any more than a
single attribute of a CharacterRun. The insertAfter() method is overloaded
and I have not yet experimented with using the CharacterProperties class but
do feel that this might - might - offer a way forward and allow us to
circumvent the above issue.
When I have the time, I will play with this some more but cannot promise
when that will be. Likewise, when I have the time, I will look at adding a
list to the document. But for now, here is some code for you to play with
and remember the following please;
* So far, I have only managed to make this work properly when using POI
version 3.2Final.
* You will need to create an empty Word document that can be used as a
template.
* To change the code in the main method to point to your template and to
write the resulting document away to the location and under the name you
require.
Yours
Mark B
public class WordTest {
public void newWordDoc(String baseFilename, String outputFilename) {
POIFSFileSystem fs = null;
HWPFDocument doc = null;
try {
fs = new POIFSFileSystem(new FileInputStream(baseFilename));
doc = new HWPFDocument(fs);
// Get the Ramge object encapsulating the text for the entire
document.
Range range = doc.getRange();
// Add a new Pargarph - it will be centered and the spacing
after
// will be 200 units (not too sure what the units are so check
in the
// javadoc).
Paragraph par1 = range.insertAfter(new ParagraphProperties(),
0);
par1.setSpacingAfter(200);
par1.setJustification((byte) 1);
// justification: 0=left, 1=center, 2=right, 3=left and right
// Insert some text into the Paragraph created in the step
above. It
// contains just a single word - 'one' - and the size of the
fint has
// been increased.
CharacterRun run1 = par1.insertAfter("one");
run1.setFontSize(36);
// paragraph with bold typeface
Paragraph par2 = run1.insertAfter(new ParagraphProperties(), 0);
par2.setSpacingAfter(200);
CharacterRun run2 = par2.insertAfter("two two two two two two "
+
"two two two two two two two");
run2.setBold(true);
// Paragraph three. This contains code showing you how to add
more
// than a single sentence of text to a Paragraph. Further, it
// demonstrates that if you have a single sentence containing
text
// that should have different treatements applied to specific
word -
// imagine for example that a single word should be italicised -
then
// you will need to create two or more CharacterRun(s) to
achieve
// this.
Paragraph par3 = run2.insertAfter(new ParagraphProperties(), 0);
par3.setFirstLineIndent(200);
par3.setSpacingAfter(200);
CharacterRun run3 = par3.insertAfter("three three three three "
+
"three three three three three three three three three "
+
"three three three three three three three three three "
+
"three three three three three three three three three "
+
"three three three three three three.");
run3.setItalic(true);
CharacterRun run4 = run3.insertAfter(" With luck, this will be "
+
"inserted after all of those threes and show how to add
" +
"more than one CharacterRun to a Paragraph.");
CharacterRun run5 = run4.insertAfter("If the treatment differs "
+
"in anyway");
//run5.setItalic(false);
CharacterRun run6 = run5.insertAfter(" in ");
//run6.setBold(true);
CharacterRun run7 = run6.insertAfter("the sentence then you will
" +
"need to create and add a");
CharacterRun run8 = run7.insertAfter(" new ");
//run7.setItalic(true);
CharacterRun run9 = run8.insertAfter("CharacterRun object and
set " +
"it's properties appropriately.");
doc.write(new FileOutputStream(outputFilename));
}
catch(Exception ex) {
System.out.println("Caught an: " + ex.getClass().getName());
System.out.println("Message: " + ex.getMessage());
System.out.println("Stacktrace follows.............");
ex.printStackTrace(System.out);
}
}
public static void main(String[] args) {
WordTest wt = new WordTest();
wt.newWordDoc("C:/temp/Template.doc", "C:/temp/Result.doc");
}
}
Prathap Iruthayaraj wrote:
>
> Hi All,
>
> Is it possible to create a MS Word Document using HWPF (POI)?
>
> I have an html page which contains of introduction text on the screen, i
> need to generate a MS Word Document with that text,
>
> I need to generate bullet and numberings too.
>
> If there are any sample code exist, please provide me the link as
> reference.
>
> Thanks,
> Prathap
>
>
--
View this message in context:
http://old.nabble.com/Need-help-to-create-MS-Word-Doc-using-POI-%28HWPF%29--tp28363016p28375134.html
Sent from the POI - User mailing list archive at Nabble.com.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]