java docx4J向word插入内容

运用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));





第三步:向docx4生成的文档中写入内容;
第三步:向docx4生成的文档中写入内容;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值