I am trying to find and replace a text different sections of header in each page using Apache poi but getting only null data, but Docx has different header sections and footer too
package com.concretepage;
import java.io.FileInputStream;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFFooter;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
public class ReadDOCXHeaderFooter {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("D:/docx/read-test.docx");
XWPFDocument xdoc=new XWPFDocument(OPCPackage.open(fis));
XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(xdoc);
//read header
for(int i=0;i<90;i++)
{
XWPFHeader header = policy.getHeader(i);
List<XWPFRun> runs = header.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
String text = r.getText(0);
if (text != null && text.contains("$$key$$")) {
text = text.replace("$$key$$", "ABCD");//your content
r.setText(text, 0);
}
}
System.out.println(header.getText());
//read footer
XWPFFooter footer = policy.getFooter(i);
System.out.println(footer.getText());
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
1.Screen shot of Docx header sections.
2.Screen shot of Docx header another section.
3.Screen shot of Docx header another section.
4.Screen Shot
3
Answers
In a
*.docx
document, which contains multiple sections, each section starts in a paragraph which has section properties set. To get the headers and footers out of section properties there is public XWPFHeaderFooterPolicy(XWPFDocument doc, org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr sectPr) constructor.Only the section properties for the last section are set in document’s body.
So the following code should get all headers and footers out of all sections in the document.
This function should do the job
Here is a code snippet that replaces all the occurrences of a key like
${firstName}
with its String value in anXWPFDocument
. All the parameters to be replaced will be stored in aMap<String, String>
.Replace the
startIndex
andendIndex
with your values$$
. Keep in mind that this implementation replaces all the occurrences ignoring the case.