java處理word已經存在很多種方法了,但是用起來都不是那么方便,而且不太靈活,而使用xml的方法可以做到非常靈活,你可以先建好模板,然后往里面填數,模板怎么建,填出來的效果就是怎么樣的。首先說說word和xml的關系,每個word它都對應著一個xml文件,也就是說你修改了xml,對應的word文件也就跟著修改了。通過word的保存功能可以將一個word文件保存為xml文件,該文件雖然是.xml格式的,但是直接雙擊打開的話還是使用word打開,所以你只能用txt將它打開,用txt打開之后將里面的一句話:<?mso-application progid="Word.Document"?>去掉,然后保存,接著就可以雙擊直接打開了,這樣使用的就是IE打開的,你這樣就可以查看里面的節點具體的構造。
最上面的主節點是<w:wordDocument>(如果不是的話,相信你將word文件保存成xml的時候使用的是07word,選擇的是:word xml文檔(*.xml),你可以選擇word 2003 xml文檔(*.xml)試試);該主節點下面有大致8個節點,其中我們要操作的就是<w:body>節點,該節點是word的正文節點,其他的節點沒有去研究;<w:body>下面包含的節點可能會有:<w:p>段落節點、<w:tbl>表格節點。
接著要做的就是在java程序中,使用dom來解析編輯xml文件,這里貼出一些代碼來供大家參考:
public Document loadXML(String filename){//////////加載xml文件
Document document = null;
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
document=builder.parse(new File(filename));
document.normalize();
}catch (Exception ex){
ex.printStackTrace();
}
return document;
}
public boolean doc2XmlFile(Document document,File targetFile){ ///////回寫xml文件
boolean flag = true;
try{
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(targetFile.toURI().getPath());
transformer.transform(source, result);
}catch(Exception ex){
flag = false;
ex.printStackTrace();
}
return flag;
}
String void function(){///////////程序入口
String rootPath=ServletActionContext.getServletContext().getRealPath("/excelTemplate")+"\\";
try{
Document document=loadXML(rootPath+"projectModel.xml");
Element root = document.getDocumentElement();
NodeList rootList=root.getChildNodes();
Node bodyNode=null;///////w:body
for(int i=0;i<rootList.getLength();i++){////////找到<w:body>節點
bodyNode=rootList.item(i);
if("w:body".equals(bodyNode.getNodeName())){
break;
}
}
NodeList nodeList=bodyNode.getChildNodes();
for(int i=0;i<nodeList.getLength();i++){
Node node=nodeList.item(i);
if("w:tbl".equals(node.getNodeName())){
dealWithTableNode(document,node);
}else if("w:p".equals(node.getNodeName())){
dealWithWPNode(document,node);
}
}
File destFile = File.createTempFile("project", ".xml");
doc2XmlFile(document,destFile);///////回寫
inputStream = new FileInputStream(destFile);/////////生成流,用于下載
fileName=URLEncoder.encode(project.getProjectName(),"utf-8")+".doc";
}catch(Exception e){
e.printStackTrace();
}
}
注意:
1、在解析編輯xml文件的時候一定好看好節點的位置,比如一般的文本內容的話可能是在<w:p>節點下的<w:r>節點下的<w:t>里設置,使用的是getTextContent()方法來獲取它的內容,setTextContent()來設置它的參數
2、對于圖片如何插入呢?首先最好在模板中插入一張圖片,主要用于定下圖片的那些格式,然后圖片必須用java轉成base64的字符串,這里也提供一個方法:
private String toBASE64codeFile(File file){
String codeString="";
try{
FileInputStream fis=new FileInputStream(file);
BASE64Encoder encoder=new BASE64Encoder();
byte[] b=new byte[228];
int count=-1,n=0;
while((count=fis.read(b))!=-1){
codeString+=encoder.encode(b);
}
return codeString;
}catch(Exception e){
e.printStackTrace();
return "";
}
}
然后找到<w:pict>節點:一般如果圖片是在table里的話,該節點就是在<w:tbl>-<w:tr>-<w:tc>-<w:p>-<w:r>節點下面,不在table里的話就是:<w:p>-<w:r>,建議仿照用IE打開的xml對照一下。然后將該節點下的<w:binData>的內容置成你所要插入的圖片的base64碼即可。