1. 程式人生 > >poi操作word文件,以07版本為參考,將word文件中圖片替換為文字(替換文字也一樣),讀圖片可選文字內容

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;
}