Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save documentprocessing/b4a597763dc9aa7c11b1311b3e5bc694 to your computer and use it in GitHub Desktop.
Save documentprocessing/b4a597763dc9aa7c11b1311b3e5bc694 to your computer and use it in GitHub Desktop.
Read Existing DOCX using Apache POI XWPF API
// Path to the input DOCX file
String inputFilePath = "input.docx";
// Path to the output DOCX file after modification
String outputFilePath = "output.docx";
// Open the DOCX file for reading
FileInputStream fis = new FileInputStream(inputFilePath);
XWPFDocument document = new XWPFDocument(fis);
// Read the paragraphs of the DOCX file
for (XWPFParagraph paragraph : document.getParagraphs()) {
System.out.println("Original Paragraph: " + paragraph.getText());
// Modify the paragraph content
if (paragraph.getText().contains("oldWord")) {
for (XWPFRun run : paragraph.getRuns()) {
String text = run.getText(0);
if (text != null && text.contains("oldWord")) {
text = text.replace("oldWord", "newWord");
run.setText(text, 0); // Update the run's text
}
}
}
}
// Save the updated document to a new file
FileOutputStream fos = new FileOutputStream(outputFilePath);
document.write(fos);
// Close the file streams
fos.close();
fis.close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment