JAva置換wordテンプレートにおけるプレースホルダDocx 4 jとPoi実装


wordテンプレートはプレースホルダ(eg:${placeholder})を動的に置き換え、新しいwordを生成します.
ネット上で検索したdocx 4 jもpoiも同じテキスト(word行データを読み取ると行データが複数のテキストに分かれる)でのプレースホルダの置換を実現しただけで、同じテキストでも改行しても実現しなかったプレースホルダに対して、docx 4 jとpoiの2つの方式をまとめて最終的にプレースホルダ置換を実現して新しいwordを生成し、2つの方式のソースコードは以下の通りである.
1、Docx 4 J実装コード

import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.wml.ContentAccessor;
import org.docx4j.wml.Text;
import org.junit.Test;

import javax.xml.bind.JAXBElement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuchao
 * @date 2020/6/8
 */
public class Test01 {

    /**
     *     Text             ,                  
     */
    private static int MAX_TEXT_SIZE = 1000000;

    @Test
    public void test() throws Exception {
        String docxFile = "/Users/liuchao/java/temp/1.docx";
        WordprocessingMLPackage template = WordprocessingMLPackage.load(new java.io.File(docxFile));
        List texts = getAllElementFromObject(
                template.getMainDocumentPart(), Text.class);
        Map map = new HashMap<>();
        map.put("${company}", "Company Name here...");
        map.put("${address}", "xxxfffadfasdf");
        map.put("${secondParty}", "xxxfffadfasdf");
        map.put("${year}", "xxxfffadfasdf");
        map.put("${month}", "xxxfffadfasdf");
        map.put("${day}", "xxxfffadfasdf");
        map.put("${money}", "1000");
        searchAndReplace(texts, map);
        template.save(new java.io.File("/Users/liuchao/java/temp/NEW.docx"));
    }


    /**
     *          
     *
     * @param obj          
     * @param toSearch         
     * @return java.util.List
     * @author liuchao
     * @date 2020/6/9
     */
    private static List getAllElementFromObject(Object obj,
                                                        Class> toSearch) {
        List result = Lists.newArrayListWithCapacity(60);
        if (obj instanceof JAXBElement) {
            obj = ((JAXBElement>) obj).getValue();
        }
        if (obj.getClass().equals(toSearch)) {
            result.add(obj);
        } else if (obj instanceof ContentAccessor) {
            List> children = ((ContentAccessor) obj).getContent();
            for (Object child : children) {
                result.addAll(getAllElementFromObject(child, toSearch));
            }
        }
        return result;
    }

    /**
     *          
     *
     * @param texts         Text    
     * @param values        key\value
     * @return void
     * @author liuchao
     * @date 2020/6/9
     */
    public static void searchAndReplace(List texts, Map values) {
        //             
        List placeholderList = getPlaceholderList(texts, values);
        if (ObjectUtil.isEmpty(placeholderList)) {
            return;
        }
        int[] currentPlaceholder;
        //        
        for (int i = 0; i < texts.size(); i++) {
            if (ObjectUtil.isEmpty(placeholderList)) {
                break;
            }
            currentPlaceholder = placeholderList.get(0);
            Text textElement = (Text) texts.get(i);
            String v = textElement.getValue();
            StringBuilder nval = new StringBuilder();
            char[] textChars = v.toCharArray();
            for (int j = 0; j < textChars.length; j++) {
                char c = textChars[j];
                if (null == currentPlaceholder) {
                    nval.append(c);
                    continue;
                }
                //             
                int start = currentPlaceholder[0] * MAX_TEXT_SIZE + currentPlaceholder[1];
                int end = currentPlaceholder[2] * MAX_TEXT_SIZE + currentPlaceholder[3];
                int cur = i * MAX_TEXT_SIZE + j;
                //   '$' '}'         
                if (!(cur >= start && cur <= end)) {
                    nval.append(c);
                }

                if (j > currentPlaceholder[3] && i >= currentPlaceholder[2]) {
                    placeholderList.remove(0);
                    if (ObjectUtil.isEmpty(placeholderList)) {
                        currentPlaceholder = null;
                        continue;
                    }
                    currentPlaceholder = placeholderList.get(0);
                }
            }
            textElement.setValue(nval.toString());
        }
    }

    /**
     *        ,           
     *
     * @param texts  Text      
     * @param values        key\value
     * @return java.util.List
     * @author liuchao
     * @date 2020/6/9
     */
    public static List getPlaceholderList(List texts, Map values) {
        //     
        int ignoreTg = 0;
        //       '$'  
        int startTg = 1;
        //       '{'  
        int readTg = 2;
        //     
        int modeTg = ignoreTg;

        //             
        List placeholderList = new ArrayList<>();
        //       0:'$'  Text texts   
        //          1:'$'   Text.getValue().toCharArray()    
        //          2: '}'  Text texts   
        //          3:'}'   Text.getValue().toCharArray()    
        int[] currentPlaceholder = new int[4];
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < texts.size(); i++) {
            Text textElement = (Text) texts.get(i);
            String newVal = "";
            String text = textElement.getValue();
            StringBuilder textSofar = new StringBuilder();
            char[] textChars = text.toCharArray();
            for (int col = 0; col < textChars.length; col++) {
                char c = textChars[col];
                textSofar.append(c);
                switch (c) {
                    case '$': {
                        modeTg = startTg;
                        sb.append(c);
                    }
                    break;
                    case '{': {
                        if (modeTg == startTg) {
                            sb.append(c);
                            modeTg = readTg;
                            currentPlaceholder[0] = i;
                            currentPlaceholder[1] = col - 1;
                        } else {
                            if (modeTg == readTg) {
                                sb = new StringBuilder();
                                modeTg = ignoreTg;
                            }
                        }
                    }
                    break;
                    case '}': {
                        if (modeTg == readTg) {
                            modeTg = ignoreTg;
                            sb.append(c);
                            newVal += textSofar.toString()
                                    + (null == values.get(sb.toString()) ? sb.toString() : values.get(sb.toString()));
                            textSofar = new StringBuilder();
                            currentPlaceholder[2] = i;
                            currentPlaceholder[3] = col;
                            placeholderList.add(currentPlaceholder);
                            currentPlaceholder = new int[4];
                            sb = new StringBuilder();
                        } else if (modeTg == startTg) {
                            modeTg = ignoreTg;
                            sb = new StringBuilder();
                        }
                    }
                    default: {
                        if (modeTg == readTg) {
                            sb.append(c);
                        } else if (modeTg == startTg) {
                            modeTg = ignoreTg;
                            sb = new StringBuilder();
                        }
                    }
                }
            }
            newVal += textSofar.toString();
            textElement.setValue(newVal);
        }
        return placeholderList;
    }

依存jar
        
            org.docx4j
            docx4j-JAXB-ReferenceImpl
            8.1.7
        
        
        
            cn.hutool
            hutool-all
            4.6.0
        
        
        
            com.alibaba
            fastjson
            1.2.60
          

 
2.Poi実装コード

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.junit.Test;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuchao
 * @date 2020/6/9
 */
public class Test03 {

    //     
    static final int ignoreTg = 0;
    //       '$'  
    static final int startTg = 1;
    //       '{'  
    static final int readTg = 2;

    @Test
    public void test() throws Exception {
        Map map = new HashMap<>();
        map.put("${company}", "Company Name here...");
        map.put("${address}", "xxxfffadfasdf");
        map.put("${secondParty}", "xxxfffadfasdf");
        map.put("${year}", "xxxfffadfasdf");
        map.put("${month}", "xxxfffadfasdf");
        map.put("${day}", "xxxfffadfasdf");
        map.put("${money}", "1000");

        XWPFDocument doc = new XWPFDocument(new FileInputStream(new File("/Users/liuchao/java/temp/1.docx")));
        List paragraphList = Lists.newArrayList(doc.getParagraphs());
        //            
        getTableParagraphs(doc, paragraphList, placeholderValues);
        //     ,              
        List placeholderList = getPlaceholderList(paragraphList, map);
        //       
        clearPlaceholder(placeholderList, paragraphList);
        BufferedOutputStream bos = FileUtil.getOutputStream(new File("/Users/liuchao/java/temp/NEW.docx"));
        doc.write(bos);
        bos.flush();
        bos.close();
        doc.close();
    }


    /**
     *           
     *
     * @param doc                   
     * @param list                     
     * @param placeholderValues       
     * @return void
     * @author liuchao
     * @date 2020/7/6
     */
    private void getTableParagraphs(XWPFDocument doc, List list, Map placeholderValues) {
        List tables = doc.getTables();
        if (ObjectUtil.isEmpty(tables)) {
            return;
        }
        tables.forEach(table -> table.getRows().forEach(row -> row.getTableCells().forEach(cell -> {
            String text = cell.getText();
            if (ObjectUtil.isEmpty(text)) {
                return;
            }
            Iterator it = placeholderValues.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                if (text.indexOf(key) != -1) {
                    list.addAll(cell.getParagraphs());
                }
            }
        })));
    }



    /**
     *        
     *
     * @param placeholderList        
     * @param paragraphList      
     * @return void
     * @author liuchao
     * @date 2020/6/10
     */
    public static void clearPlaceholder(List placeholderList, List paragraphList) {
        if (ObjectUtil.isEmpty(placeholderList)) {
            return;
        }
        int[] currentPlaceholder = placeholderList.get(0);
        StringBuilder tempSb = new StringBuilder();
        for (int i = 0; i < paragraphList.size(); i++) {
            XWPFParagraph p = paragraphList.get(i);
            List runs = p.getRuns();
            for (int j = 0; j < runs.size(); j++) {
                XWPFRun run = runs.get(j);
                String text = run.getText(run.getTextPosition());
                StringBuilder nval = new StringBuilder();
                char[] textChars = text.toCharArray();
                for (int m = 0; m < textChars.length; m++) {
                    char c = textChars[m];
                    if (null == currentPlaceholder) {
                        nval.append(c);
                        continue;
                    }
                    //   '$' '}'         
                    int start = currentPlaceholder[0] * 1000000 + currentPlaceholder[1] * 500 + currentPlaceholder[2];
                    int end = currentPlaceholder[3] * 1000000 + currentPlaceholder[4] * 500 + currentPlaceholder[5];
                    int cur = i * 1000000 + j * 500 + m;
                    if (!(cur >= start && cur <= end)) {
                        nval.append(c);
                    } else {
                        tempSb.append(c);
                    }
                    //          ,           
                    if (tempSb.toString().endsWith("}")) {
                        placeholderList.remove(0);
                        if (ObjectUtil.isEmpty(placeholderList)) {
                            currentPlaceholder = null;
                            continue;
                        }
                        currentPlaceholder = placeholderList.get(0);
                        tempSb = new StringBuilder();
                    }
                }
                run.setText(nval.toString(), run.getTextPosition());

            }
        }
    }

    /**
     *        ,           
     *
     * @param paragraphList    
     * @param map                  key\value
     * @return java.util.List
     * @author liuchao
     * @date 2020/6/10
     */
    public static List getPlaceholderList(List paragraphList, Map map) {
        //             
        List placeholderList = new ArrayList<>();
        //       0:'$'   XWPFParagraph     
        //          1:'$'   XWPFRun     
        //          2:'$'   text.toCharArray()    
        //          3: '}'   XWPFParagraph     
        //          4: '}'   XWPFRun     
        //          5:'}'   text.toCharArray()    
        int[] currentPlaceholder = new int[6];

        //     
        int modeTg = ignoreTg;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < paragraphList.size(); i++) {
            XWPFParagraph p = paragraphList.get(i);
            List runs = p.getRuns();
            for (int j = 0; j < runs.size(); j++) {
                XWPFRun run = runs.get(j);
                String text = run.getText(run.getTextPosition());
                char[] textChars = text.toCharArray();
                String newVal = "";
                StringBuilder textSofar = new StringBuilder();
                for (int m = 0; m < textChars.length; m++) {
                    char c = textChars[m];
                    textSofar.append(c);
                    switch (c) {
                        case '$': {
                            modeTg = startTg;
                            sb.append(c);
                        }
                        break;
                        case '{': {
                            if (modeTg == startTg) {
                                sb.append(c);
                                modeTg = readTg;
                                currentPlaceholder[0] = i;
                                currentPlaceholder[1] = j;
                                currentPlaceholder[2] = m - 1;
                            } else {
                                if (modeTg == readTg) {
                                    sb = new StringBuilder();
                                    modeTg = ignoreTg;
                                }
                            }
                        }
                        break;
                        case '}': {
                            if (modeTg == readTg) {
                                modeTg = ignoreTg;
                                sb.append(c);
                                String val = map.get(sb.toString());
                                if (ObjectUtil.isNotEmpty(val)) {
                                    newVal += textSofar.toString() + val;
                                    placeholderList.add(currentPlaceholder);
                                    textSofar = new StringBuilder();
                                }
                                currentPlaceholder[3] = i;
                                currentPlaceholder[4] = j;
                                currentPlaceholder[5] = m;
                                currentPlaceholder = new int[6];
                                sb = new StringBuilder();
                            } else if (modeTg == startTg) {
                                modeTg = ignoreTg;
                                sb = new StringBuilder();
                            }
                        }
                        default: {
                            if (modeTg == readTg) {
                                sb.append(c);
                            } else if (modeTg == startTg) {
                                modeTg = ignoreTg;
                                sb = new StringBuilder();
                            }
                        }
                    }
                }
                newVal += textSofar.toString();
                run.setTextPosition(0);
                run.setText(newVal, run.getTextPosition());
            }
        }
        return placeholderList;
    }

依存jar
            
            
                cn.hutool
                hutool-all
                4.6.0
            
            
            
                com.alibaba
                fastjson
                1.2.60
              
            
                org.apache.poi
                poi
                4.1.1
            
            
                org.apache.poi
                poi-ooxml
                4.1.1
            
            
                org.apache.poi
                poi-ooxml-schemas
                4.1.1