如何用Apache POI在Word中绘制带填充色的矩形?VML标签报错求解
解决Apache POI插入VML形状报错的问题
问题核心分析
你的代码存在两个关键错误:
- 逻辑完全错位:将VML形状的XML拿去解析成
CTNumbering(编号对象),这和插入形状的需求完全不相关,属于API误用。 - 缺少命名空间声明:VML的
v前缀、WordML的w前缀未在XML中绑定对应命名空间,导致XML解析器无法识别这些标签。
正确实现思路
要在Word文档顶部添加红色矩形,需将VML形状插入到页眉或首段中,同时给XML补充完整的命名空间声明,并设置矩形的红色填充样式。
修正后的代码示例
import org.apache.poi.xwpf.usermodel.*; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; import java.io.FileOutputStream; public class WordRedRectDemo { public static void main(String[] args) throws Exception { XWPFDocument document = new XWPFDocument(); // 创建页眉,将红色矩形放在文档顶部区域 XWPFHeader header = document.createHeader(HeaderFooterType.DEFAULT); XWPFParagraph para = header.createParagraph(); para.createRun(); // 构造带命名空间、红色填充的VML矩形XML String vmlRectXml = "" + "<w:pict xmlns:w=\"http://schemas.microsoft.com/office/word/2003/wordml\" xmlns:v=\"urn:schemas-microsoft-com:vml\">" + " <v:rect style=\"width:595pt;height:25pt;position:absolute;left:0;top:0;\" strokecolor=\"#000000\">" + " <v:fill on=\"true\" color=\"#ff0000\"/>" + " </v:rect>" + "</w:pict>"; // 操作段落底层XML,插入VML形状 CTP ctp = para.getCTP(); CTR ctr = ctp.getRArray(0); ctr.addNewPict().set(vmlRectXml); // 添加正文测试内容 XWPFParagraph bodyPara = document.createParagraph(); XWPFRun bodyRun = bodyPara.createRun(); bodyRun.setText("文档正文内容示例"); // 保存文档 try (FileOutputStream fos = new FileOutputStream("red_rect_top.docx")) { document.write(fos); } document.close(); } }
关键说明
- 命名空间绑定:必须在
w:pict标签中声明xmlns:w和xmlns:v两个命名空间,这是XML解析器识别v:、w:前缀的必要条件。 - 样式与定位:通过
style属性设置矩形的宽、高、绝对定位;利用v:fill标签设置红色填充,strokecolor设置边框颜色。 - 插入位置:示例将矩形放在页眉,确保它固定显示在文档顶部;若需放在正文首段,直接操作正文段落的
CTP对象即可。
内容的提问来源于stack exchange,提问作者Jeet
相关产品推荐
相关产品推荐

