Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With Java: replace string in MS Word file [closed]

Tags:

java

ms-word

We need a Java library to replace strings in MS Word files.

Can anyone suggest?

like image 535
gusti Avatar asked Dec 07 '09 14:12

gusti


2 Answers

While there is MS Word support in Apache POI, it is not very good. Loading and then saving any file with other than the most basic formatting will likely garble the layout. You should try it out though, maybe it works for you.

There are a number of commercial libraries as well, but I don't know if any of them are any better.

The crappy "solution" I had to settle for when working on a similar requirement recently was using the DOCX format, opening the ZIP container, reading the document XML, and then replacing my markers with the right texts. This does work for replacing simple bits of text without paragraphs etc.

private static final String WORD_TEMPLATE_PATH = "word/word_template.docx";
private static final String DOCUMENT_XML = "word/document.xml";

/*....*/

final Resource templateFile = new ClassPathResource(WORD_TEMPLATE_PATH);

final ZipInputStream zipIn = new ZipInputStream(templateFile.getInputStream());
final ZipOutputStream zipOut = new ZipOutputStream(output);

ZipEntry inEntry;
while ((inEntry = zipIn.getNextEntry()) != null) {
    final ZipEntry outEntry = new ZipEntry(inEntry.getName());
    zipOut.putNextEntry(outEntry);

    if (inEntry.getName().equals(DOCUMENT_XML)) {
        final String contentIn = IOUtils.toString(zipIn, UTF_8);
        final String outContent = this.processContent(new StringReader(contentIn));
        IOUtils.write(outContent, zipOut, UTF_8);
    } else {
        IOUtils.copy(zipIn, zipOut);
    }

    zipOut.closeEntry();
}

zipIn.close();
zipOut.finish();

I'm not proud of it, but it works.

like image 53
Henning Avatar answered Oct 25 '22 15:10

Henning


I would suggest the Apache POI library:

http://poi.apache.org/

Looking more - it looks like it hasn't been kept up to date - Boo! It may be complete enough now to do what you need however.

like image 39
Nick Fortescue Avatar answered Oct 25 '22 14:10

Nick Fortescue