docx4j 动态生成表格 (一 )

 使用docx4j模板动态制作表格代码实现过程(一 ),模板在附件中 ,可以执行代码看结果

模板式样:


docx4j 动态生成表格 (一 )_第1张图片
 

最终式样 :


docx4j 动态生成表格 (一 )_第2张图片
 

制作过程 :

   将模板制作好后,变量使用'${}'表示。使用解压缩工具打开word2007,解压并打开word/document.xml文件确保其格式如下图 :


docx4j 动态生成表格 (一 )_第3张图片
 
docx4j 动态生成表格 (一 )_第4张图片
 

 

 执行代码 :

import java.util.HashMap;
import java.util.List;

import javax.xml.bind.JAXBException;

import org.docx4j.TraversalUtil;
import org.docx4j.XmlUtils;
import org.docx4j.finders.ClassFinder;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.Tbl;
import org.docx4j.wml.Tr;

/**
 * 个人实例
 * 加载多个模板,其中一个模板有循环出现的表格数据,有图片贴图做用户名
 * 最终将多个模板合并到一个输入流或者是合并到一个文档中
 * 
 * @author Administrator
 *
 */
public class MyExapmle2 {
	private static final  String templetate_img_docx  = "";
	
	private static final  String tale_templetate_docx  = "\\myexamples\\tale_templetate.docx";
	
	private static final  String tale_output_docx  = "\\myexamples\\tale_output.docx";
	
	public static void main(String[] args) throws Docx4JException, JAXBException {
		
		//加载表格类型模板
		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
				.load(new java.io.File(System.getProperty("user.dir")+tale_templetate_docx));
		//定位需要替换的位置
		ClassFinder finder = new ClassFinder(Tbl.class); // <----- change this to suit
		MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
		new TraversalUtil(documentPart.getContent(), finder);
		System.out.println(String.format("查找到%d个表格 "    , finder.results.size() ));
		
		Tbl table_selected =  (Tbl) finder.results.get(1);
		List trs = table_selected.getContent();
		org.docx4j.wml.Tr templetate_row = (Tr)trs.get(1);
		//替换第二行的数据
		Listtds = templetate_row.getContent();
		HashMap datamap = new HashMap();
		datamap.put("id", "1");
		datamap.put("name", "张三");
		datamap.put("age", "12");
		datamap.put("p", "山东");
		datamap.put("c", "青岛");
		
		HashMap datamap2 = new HashMap();
		datamap2.put("id", "2");
		datamap2.put("name", "李四");
		datamap2.put("age", "12");
		datamap2.put("p", "山东");
		datamap2.put("c", "青岛");
		
		String templetate_row_string = XmlUtils.marshaltoString(templetate_row);
		Object newTr = XmlUtils.unmarshallFromTemplate(templetate_row_string,datamap);
		table_selected.getContent().add(newTr);
		
		newTr = XmlUtils.unmarshallFromTemplate(templetate_row_string,datamap2);
		table_selected.getContent().add(newTr);
		//移除第一行
		table_selected.getContent().remove(1);
		//保存文件
		String filename = System.getProperty("user.dir") + tale_output_docx;
		wordMLPackage.save(new java.io.File(filename) );
	}
}

 

 模板在附件中 ,可以执行代码看结果

 

你可能感兴趣的:(java,docx4j)