How can I update the page header of a .docx
file using the Apache POI 3.7 API?
问题:
回答1:
First up, call getHeaderFooterPolicy() on your XWPFDocument, which returns a HeaderFooterPolicy. From that, you can identify the appropriate header for your page (eg Default, First Page etc)
Once you have the appropriate XWPFHeader that you want to change, then you can go about editing it as any other document part. You can fetch the tables, the paragraphs etc, then remove them, add new ones, change the text of them etc. It's all the same process then as editing the main document.
回答2:
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 aorg.apache.poi.hwpf.usermodel.HeaderStores
, passing it yourHWPFDocument
. Finally, theHeaderStores
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.
回答3:
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