poi操作word文档,以07版本为参考,将word文档中图片替换为文本(替换文本也一样),读图片可选文字内容


1、先简单介绍下word07版本以后的存储格式,word 07版本以后主要是以xml格式存储。如果想查看详情可将后缀名改为zip,再查看压缩文件可查看到各种文件,其中document.xml就是word主要展现给我们大家所看到的内容。

2.根据第一步的描述,我查看了document.xml,如果有图片,xml文件里会有w:drawing节点。解题思路就从这里来,把这个节点去掉,再替换成为一个文本节点。

3.查看document.xml时我们会发现每个文本内容都是在w:t节点下的,但文本内容并不是w:t节点下的值,而是w:t节点下还隐藏了一个#:text节点,文本内容是装在#:text节点下的,#:text节点在document.xml并查看不到,就是这花了我比较多的时间。

详细代码:

XWPFDocument document// docx word文档的document

Node node = document.getDocument().getDomNode();//得到文档跟节点,这里的节点大概跟document.xml看到的是一致的
Node wcNode = Poi4WordUtil.getWtNode(node);//获取文档的一个w:t节点供后续拷贝

this.setNodeData(node, wcNode, ssId, instId, dataDate);


/**
* 把图片节点换成文本节点

* @param node
* @param wcNode

*/
private void setNodeData(Node node, Node wcNode) {
if ("w:drawing".endsWith(node.getNodeName())) {
Node parentNode = node.getParentNode();

Node cloneNode = wcNode.cloneNode(true);//一个wt节点,它含包含一个#:text节点,将#:text节点的值替换为自己想要的值
Node child = cloneNode.getFirstChild();
String descr = Poi4WordUtil.getPicDescr(node);//获取图片可选文字的内容

child.setNodeValue(“要设置的值”);

parentNode.replaceChild(cloneNode, node);
}
if (node.hasChildNodes()) {
NodeList temp = node.getChildNodes();
for (int i = 0; i < temp.getLength(); i++) {
setNodeData(temp.item(i), wcNode,);
}
}
}


/**
* 获取word文档中其中的一个w:c节点,方便根据需要替换节点时作copy使用

* @param node
* @return
*/
public static Node getWtNode(Node node) {
if ("w:t".equals(node.getNodeName())) {
return node;
} else {
if (node.hasChildNodes()) {
NodeList temp = node.getChildNodes();
Node wcNode = null;
for (int i = 0; i < temp.getLength(); i++) {
wcNode = getWtNode(temp.item(i));
if (wcNode != null)
break;
}
return wcNode;
}
return null;
}
}

/**
* 获取word文档里图片里可选文字的内容,传入的节点为w:drawing节点

* @param node
* @return
*/
public static String getPicDescr(Node node) {
NodeList childNodes = node.getFirstChild().getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node item = childNodes.item(i);
if ("wp:docPr".equals(item.getNodeName())) {
NamedNodeMap attributes = item.getAttributes();
return attributes.getNamedItem("descr").getNodeValue();
}
}
return null;
}



猜你喜欢

转载自blog.csdn.net/yy455363056/article/details/49473127