dom4j解析word的xml模板生成word文档

1、编辑word模板,需要动态填充数据的用对应的占位符替代,表格的话只保留表格的头即可。
2、dom4j读取模板,然后进行填充数据。
3、输出word格式的xml。

@SuppressWarnings("unchecked")
public class Test2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		File file = new File("c:\\t2007.xml");
		handleWord(file);
	}

	public static void handleWord(File file) throws Exception {

		Map map = new HashMap();
		map.put("orderCd", "10004");
		map.put("workContent", "word工作测试");
		map.put("preparePerson", "王五");
		map.put("prepareTime", "2010年10月2日");
		map.put("backPerson", "李四");
		map.put("backDate", "2012年12月23日");
		map.put("bjclPreparePerson", "绿茶");
		map.put("bjclPrepareTime", "2012年12月9日");
		map.put("bjclBackPerson", "可乐");
		map.put("bjclBackDate", "2014年1月2日");
		List datas = new ArrayList();
		List temp = new ArrayList();
		temp.add(new Object[] { "1",
				"http://schemas.openxmlformats.org/wordprocessingml/2006/main",
				"b1", "c1", "c1" });
		temp.add(new Object[] { "1",
				"http://schemas.openxmlformats.org/wordprocessingml/2006/main",
				"b2", "c2", "c1" });
		temp.add(new Object[] { "1", "a3", "b3", "c3", "c1" });
		temp.add(new Object[] { "2", "a3", "b3", "c3", "c1" });
		temp.add(new Object[] { "3", "a3", "b3", "c3", "c1" });
		temp.add(new Object[] { "3", "a3", "b3", "c3", "c1" });
		temp.add(new Object[] { "3", "a3", "b3", "c3", "c1" });
			datas.add(temp);
		temp = new ArrayList();
		temp.add(new Object[] { "1", "aa1", "bb1", "cc1", "c1" });
		temp.add(new Object[] { "2",
				"http://schemas.openxmlformats.org/wordprocessingml/2006/main",
				"bb2", "cc2", "c1" });
		temp.add(new Object[] { "3", "aa3", "bb3", "cc3", "c1" });
		datas.add(temp);

		SAXReader reader = new SAXReader();
		
		InputStream inputStream=new FileInputStream(file);
//		inputStream.read(data);
		
		Document doc = reader.read(inputStream);// 获取document
		replaceText(doc, map);
		appendTable(doc, datas);
		
		DefaultXPath xpath = new DefaultXPath("//w:document//w:body//w:tbl");
		xpath
				.setNamespaceURIs(Collections
						.singletonMap("w",
								"http://schemas.openxmlformats.org/wordprocessingml/2006/main"));
		List tables = xpath.selectNodes(doc);

		handle(doc,tables.get(0),new String[]{"0"});
		XMLWriter writer = null;
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		writer = new XMLWriter(new FileOutputStream(new File("c:\\o2007.xml")),
				format);
	
		writer.write(doc);
		writer.flush();
		writer.close();

	}

	/**
	 * 
	 * @param document
	 * @param map
	 * @throws Exception
	 */
	public static void replaceText(Document document, Map map)
			throws Exception {
		DefaultXPath xpath = new DefaultXPath("//w:document//w:body//w:t");
		xpath
				.setNamespaceURIs(Collections
						.singletonMap("w",
								"http://schemas.openxmlformats.org/wordprocessingml/2006/main"));

		List texts = xpath.selectNodes(document);
		for (Element element : texts) {
			if ("".equals(element.getTextTrim()))
				continue;
			for (Map.Entry entry : map.entrySet()) {
				if (element.getText().contains(entry.getKey())) {
					element.setText(entry.getValue());
				}
			}
		}
	}

	/**
	 * 
	 * @param document
	 * @param list
	 * @throws Exception
	 */
	public static void appendTable(Document document, List datas)
			throws Exception {
		DefaultXPath xpath = new DefaultXPath("//w:document//w:body//w:tbl");
		xpath
				.setNamespaceURIs(Collections
						.singletonMap("w",
								"http://schemas.openxmlformats.org/wordprocessingml/2006/main"));
		List tables = xpath.selectNodes(document);
		List data = null;
		Element table, tr, td, p, t, r;
		Object[] obj;
		// table
		for (int i = 0; i < tables.size(); i++) {
			if (i >= datas.size())
				break;
			data = (List) datas.get(i);
			// 取得一个table对象
			table = tables.get(i);
			// 行数
			for (int j = 0; j < data.size(); j++) {
				obj = (Object[]) data.get(j);
				tr = table.addElement("w:tr");
				// 对列对象进行数据填充
				for (int k = 0; k < obj.length; k++) {
					td = tr.addElement("w:tc");
					td.addAttribute("w:val", (String) obj[k]);
					p = td.addElement("w:p");
					r = p.addElement("w:r");
					t = r.addElement("w:t");
					t.setText((String) obj[k]);
				}
			}
		}
	}

	public static void handle(Document document,Element table,String[] columnIdx) throws Exception {

		Element  line, column;
		List lines,columns;
		Attribute attribute = null;
		lines = table.elements("tr");
		
		MultiHashMap multiHashMap = new MultiHashMap();
		for (int i = 1; i < lines.size(); i++) {
			line = lines.get(i);
			columns = line.elements("tc");
			for(String index:columnIdx)
			{
				column = columns.get(Integer.parseInt(index));
				attribute = column.attribute("w:val");
				multiHashMap.put(attribute.getText(), column);
			}

		}
		//进行合并单元格
		String key = null;
		Collection collection = null;
		Element[] vMergeArr = null;
		boolean flag;
		for (Iterator iterator = multiHashMap.keySet().iterator(); iterator
				.hasNext();) {
			flag = true;
			key = (String) iterator.next();
			collection = multiHashMap.getCollection(key);
			if (collection.size() > 1) {
				vMergeArr = (Element[]) collection.toArray(new Element[0]);
				for (Element e : vMergeArr) {
					if (flag) {
						e.addElement("w:vMerge").addAttribute("w:val",
								"restart");
						flag = false;
					} else {
						e.addElement("w:vMerge");
					}
				}
			}
		}
	}
}

 

你可能感兴趣的:(java/word)