Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a .docx file's page header using Apache POI

How can I update the page header of a .docx file using the Apache POI 3.7 API?

like image 647
Jalal Sordo Avatar asked Sep 10 '25 23:09

Jalal Sordo


2 Answers

Since your document is in .docx format, you'll need to use the XWPF component API of the POI project. You may find the org.apache.poi.xwpf.usermodel.XWPFHeader class useful (Javadoc), but I've never used it myself.

I couldn't find a good reference for doing this with XWPF, but the following instructions describe accessing headers with HWPF, the analagous interface for older Word documents (AKA .doc docs):

To get at the headers and footers of a Word document, first create a org.apache.poi.hwpf.HWPFDocument. Next, you need to create a org.apache.poi.hwpf.usermodel.HeaderStores, passing it your HWPFDocument. Finally, the HeaderStores gives you access to the headers and footers, including first / even / odd page ones if defined in your document. Additionally, HeaderStores provides a method for removing any macros in the text, which is helpful as many headers and footers do end up with macros in them.

The page those instructions are from implies that header support was never that good in HWPF, let alone XWPF. For more bad news, this other Apache page makes it sound like XWPF development has all but stalled. It's possible that what you want to do is planned but not supported yet.

like image 102
Pops Avatar answered Sep 13 '25 12:09

Pops


Check out Writing Microsoft Word Documents in Java With Apache POI

I never worked with Word file before, but done so with POI library for excel stuff, they are quite easy to follow (they model the row, column, sheet etc for excel) so I am assuming they will be equally easy to do for Word files.

And do quick read on their guide Apache POI - HWPF - Java API to Handle Microsoft Word Files

like image 20
TS- Avatar answered Sep 13 '25 13:09

TS-