Forums Register Login

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

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
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 https://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).
+Pie Number of slices to send: Send
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!
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
WARNING! Do not activate jet boots indoors or you will see a tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 15136 times.
Similar Threads
InvalidFormatException
Apache POI 2007 word documents
MS-Word 2007
Convert .doc file to .txt file
Problems reading in .docx files in java
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 15:12:41.