Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

trying to edit a doc/docx file in Java using apachi poi library

 
Paul Scholsy
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The plan is to change a word or phrase in the file and save the new output without changing the format ( font, size, paragraphs, etc) of the original file. So I would like the new file to be an exact copy of the original file except for the changed words.

I know I have to use the apache poi libraries, I am doing this



However the issue is when I come to save it, all the formatting is gone.

Can someone please help me figure out what functions or objects I can use/should use to solve this?
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, of course. What you're doing is extracting the plain text, and then saving it as a text file - so the result is a text file, not a word file. You need to use the methods of the POI API to replace the words in the Word file.

There's some sample code that does search/replace for doc files in http://www.coderanch.com/t/534754/java/java/Editing-pdf-word-content-text; you'll have to adapt it to work with XWPF files (different POI packages, but the classes and methods should be similar).
 
Paul Scholsy
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank Ulf Dittmer, I was looking at that post before I posted mine but I couldnt get that to work . I will give it another go and post back the results. Appreciate the quick reply!
 
Paul Scholsy
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ulf Dittmer I still dont seem able to figure how to get this done. I looked at the sample code over and over, the replacement function seems to be incomplete and also the example is missing the save/write function.
I would truly appreciate all the help this community can offer
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I haven't looked at that code in a long time; why do you think it's incomplete?

And yes, it works on an in-memory document;loading and saving you'd handle like you would handle it for another other in-memory POI document. Check out the POI web site section about spreadsheets - that is much better documented, and has example code for loading/saving. It would be largely analogous for word documents.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic