Document document = new SAXReader().read(this.getClass().getResource("/resources/reportWordTemplate.xml"));
Element root = document.getRootElement();
//填充页眉
Element headPackage = (Element) root.selectSingleNode("/pkg:package/pkg:part[@pkg:name='/word/header1.xml']");
Element head = headPackage.element("xmlData").element("hdr");
Element productModelAndOCS = (Element) head.selectSingleNode("//w:p/w:r[@id='productModelAndOCS']/w:t");
productModelAndOCS.setText(productModel + "-" + OCS);
Element customerText = (Element) head.selectSingleNode("//w:p/w:r[@id='customer']/w:t");
customerText.setText(customer);
//填充页脚
Element footPackage = (Element) root.selectSingleNode("/pkg:package/pkg:part[@pkg:name='/word/footer1.xml']");
Element foot = footPackage.element("xmlData").element("ftr");
Element bomElement = (Element) foot.selectSingleNode("//w:p/w:r[@id='bom']/w:t");
bomElement.setText(bomNumber);
//填充表格
Element body = (Element) root.selectSingleNode("/pkg:package/pkg:part[@pkg:name='/word/document.xml']");
Element table = body.element("xmlData").element("document").element("body").element("tbl");
Element tr = (Element) table.selectSingleNode("//w:tr[@id='trtemplate']");
if(tr != null){
table.remove(tr);
for (String[] data : datas){
Element datatr = (Element) tr.clone();
if(datatr.elements("tc").size() != data.length){
throw new Exception("数据与模板字段数不一致!");
}
for (int i = 0; i < data.length; i++){
Element wt = datatr.elements("tc").get(i).element("p").elements("r").get(0).element("t");
wt.setText(data[i]);
}
table.add(datatr);
}
}
|