运用docx4j,向Word模板中插入内容和表格,生成新的Word文档。(仅使用于word2007及以上版本)
首先:读取Word模板文件流;
- String realpath = request.getServletContext().getRealPath("\\template\\sbxx\\sbsydjb.docx");
- File file = new File(realpath);
-
第二步:使用docx4j读入流生成新的文档;
- OpcPackage opcPackage = OpcPackage.load(new FileInputStream(file),"1");
- WordprocessingMLPackage wordMLPackage = (WordprocessingMLPackage) opcPackage;
第三步:向docx4生成的文档中写入内容;
- P p = new P();
- Docx4jUtils.addParaContent(p, "设备编号:", 24, null, false, false);
- Docx4jUtils.addParaContent(p, sbbh, 24, null, true, false);
- Docx4jUtils.addSpace2Para(p, 3, null, null);
-
- Docx4jUtils.addParaContent(p, "设备名称:", 24, null, false, false);
- Docx4jUtils.addParaContent(p, sbmc, 24, null, true, false);
- Docx4jUtils.addSpace2Para(p, 3, null, null);
-
- Docx4jUtils.addParaContent(p, "型号:", 24, null, false, false);
- Docx4jUtils.addParaContent(p, sbxh, 24, null, true, false);
- Docx4jUtils.addSpace2Para(p, 3, null, null);
-
- wordMLPackage.getMainDocumentPart().addObject(p);
第四步:向docx4生成的文档中写入表格;
- //插入表格
- Tbl table = Context.getWmlObjectFactory().createTbl();
-
- // 给表格加上边框
- Docx4jUtils.addBorders(table);
-
- // 初始化表头
- ObjectFactory factory1 = Context.getWmlObjectFactory();
- Tr tableRow1 = factory1.createTr();
- Docx4jUtils.addTableCell(wordMLPackage, tableRow1, "name");
- table.getContent().add(tableRow1);
-
- for(int i=0;i<lists.size();i++){
-
- ObjectFactory factory = Context.getWmlObjectFactory();
- Tr tableRow = factory.createTr();
- Docx4jUtils.addTableCell(wordMLPackage, tableRow, "value");
-
- table.getContent().add(tableRow);
- }
- // 设置单元格对其方式
- Docx4jUtils.setTblAlign(table);
- Docx4jUtils.addObjectForTbl(wordMLPackage, table);
最后:保存成docx格式文档;
- // 设置单元格对其方式
- Docx4jUtils.setTblAlign(table);
- Docx4jUtils.addObjectForTbl(wordMLPackage, table);
- //保存成Word
- String folderpath = request.getServletContext().getRealPath("\\downloadfile\\");
- String savepath = request.getServletContext().getRealPath("\\downloadfile\\test.docx");
- File f = new File(folderpath);
- if(!f.exists()){
- f.mkdirs();
- }
- wordMLPackage.save(new java.io.File(savepath));