步骤一:把模板后缀名修改为zip解压
步骤二:打开word/document.xml
步骤三:把所有${不连续的修改为连续,如${1,}修改为${1}
步骤五:选中解压内容压缩为zip,修改后缀名为docx
下面举个实际例子:
如果数据是静态的
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
HashMap staticMap = getStaticData();
// 替换普通变量
documentPart.variableReplace(staticMap);
// 保存结果
saveWordPackage(wordMLPackage, outputfilepath);
替换完成,后面的东西没必要看了。
如果内容中有普通表格且表格内容有动态数据,如
层次、民族数据是动态的,保证表格有数据,即打开word/document.xml看到如下内容tc下面只有一个t:
参考例子如下:
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.xml.bind.JAXBElement;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.docx4j.TraversalUtil;
import org.docx4j.XmlUtils;
import org.docx4j.dml.chart.CTChartSpace;
import org.docx4j.dml.chart.CTNumDataSource;
import org.docx4j.dml.chart.CTNumVal;
import org.docx4j.dml.chart.CTPieChart;
import org.docx4j.dml.chart.CTPieSer;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.DrawingML.Chart;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.openpackaging.parts.relationships.Namespaces;
import org.docx4j.openpackaging.parts.relationships.RelationshipsPart;
import org.docx4j.relationships.Relationship;
import org.docx4j.wml.Body;
import org.docx4j.wml.Br;
import org.docx4j.wml.ContentAccessor;
import org.docx4j.wml.Document;
import org.docx4j.wml.P;
import org.docx4j.wml.R;
import org.docx4j.wml.Tbl;
import org.docx4j.wml.Tc;
import org.docx4j.wml.TcPr;
import org.docx4j.wml.TcPrInner.VMerge;
import org.docx4j.wml.Text;
import org.docx4j.wml.Tr;
import org.docx4j.wml.TrPr;
import org.junit.Test;
public class Docx4j_替换模板 {
private String inputfilepath = "E:/test_tmp/0904/test_docx.docx";
private static final String outputfilepath = "e:/test_tmp/0904/sys_" + System.currentTimeMillis() + ".docx";
public static org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory();
@Test
public void testReplaceTemplateDocx() throws Exception {
replaceTemplateDocx();
}
public void replaceTemplateDocx() throws Exception {
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
HashMap staticMap = getStaticData();
// 替换普通变量
documentPart.variableReplace(staticMap);
Document document = (Document) documentPart.getContents();
Body body = document.getBody();
MyTblFinder tblFinder = new MyTblFinder();
new TraversalUtil(body, tblFinder);
// 替换表格模板第三行数据
Tbl firstTbl = tblFinder.getTbls().get(0);
List