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

狂风中的少年 提交于 2019-12-06 00:33:38

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.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!