如何使用POI操作Word文本框中的内容
1、第一步,使用输入流打开文件,并获得文档的XWPFDocument对象。然后获得文档的所有段落,进而获得要操作的文本框所在的段落,具体使用时候,可以通过判断或者print操作得知要操作的文本框到底是哪一段。
FileInputStream fis = new FileInputStream("e:/file.docx");
XWPFDocument doc = new XWPFDocument(fis);
List<XWPFParagraph> paragraphList = doc.getParagraphs();
XWPFParagraph paragraph = paragraphList.get(10);
文本框在Word中显示如图所示:

2、第二步,获取XWPFParagraph的XmlObject,然后获得XmlObject对象的游标。可以通过打印XmlObject来得知当前XML的内容,也可以使用XmlCursor的getName方法和getTextValue方法来查看当前游标所在位置的Node及Node的值。
XmlObject object = paragraph.getCTP().getRArray(1);
XmlCursor cursor = object.newCursor();
3、第四步,通过移动游标,找到要修改的文本所在位置,然后使用游标的setTextValue来设置其值。
//修改第一处文本:
cursor.toChild(1); cursor.toChild(0); cursor.toChild(3); cursor.toChild(0); cursor.toChild(0); cursor.toChild(3); cursor.toChild(1); cursor.setTextValue("First");
// 修改第二处文本
cursor.toParent(); cursor.toParent(); cursor.toChild(1);
cursor.toChild(3); cursor.toChild(1);
cursor.setTextValue("Second");
4、第四步,保存文件、关闭输入输出流。
FileOutputStream fos = new FileOutputStream("e:/export.docx");
doc.write(fos);
fos.flush();
fos.close();
fis.close();
修改后的文本框如图所示:
