poi word模板替换

poi word模板替换

doc模板替换

引入poi

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.9</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.9</version>
        </dependency>

doc模板
在这里插入图片描述
word内容替换方法

/**
     * word模板替换
     *
     * @param dataJSON       数据源
     * @param tmePath        模板地址
     * @param exportPath     导出文件路径
     * @param exportFileName 导出文件名称带后缀,后缀为.doc (eg:test.doc)
     * @return
     */
    public File docWrite(JSONObject dataJSON,String tmePath, String exportPath, String exportFileName) {
        FileUtil.createDir(exportPath);
        try {
            InputStream in = this.getClass().getClassLoader().getResourceAsStream(tmePath);
            HWPFDocument doc = new HWPFDocument(in);
            Range range = doc.getRange();
            //把range范围内的${X}替换为当前的X
            range.replaceText("${student_number}", dataJSON.getString("student_number"));
            range.replaceText("${student_name}", dataJSON.getString("student_name"));
            File outFile = new File(exportPath + "/" + exportFileName);
            OutputStream os = new FileOutputStream(outFile);
            doc.write(os);
            this.closeStream(in);
            this.closeStream(os);
            return outFile;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

替换后word
在这里插入图片描述

docx模板替换

docx模板
在这里插入图片描述

docx替换方法

public class DOCXDocument {

    /**
     * 替换文本中的回车
     *
     * @param context 需要替换的字符串
     * @return
     */
    public static String replaceEnter(String context) {
        if (context != null) {
            String pattern = "[\\r\\n|\\r|\\n|\\n\\r]{1,}";
            String result = context.replaceAll(pattern, "####");
            return result;
        } else {
            return "";
        }
    }

    public XWPFDocument docxwrite(JSONObject jsonObject, XWPFDocument docx) {

        String split = null;

        try {
            split = jsonObject.get("split").toString();
        } catch (Exception e) {
            split = null;
        }

        try {

            List<XWPFParagraph> paragraphsList = docx.getParagraphs();

            for (XWPFParagraph xwpfParagraph : paragraphsList) {

                List<XWPFRun> runs = xwpfParagraph.getRuns();

                Boolean bool = false;
                String var = "";

                for (XWPFRun xwpfRun : runs) {
                    String text = xwpfRun.getText(0);
                    if (bool) {
                        var += text;
                    }

                    if (text != null) {
                        if (text.indexOf("${") == 0
                                && text.indexOf("}") == text.length() - 1) {
                            var = text;
                            String a = var.substring(2, var.length() - 1);

                            Object valueobj = JSONToolsUtil.getValue(jsonObject, a,
                                    split);
                            String value = "";

                            if (valueobj != null) {
                                value = valueobj.toString();
                            }
                            xwpfRun.setText(value, 0);
                            var = "";

                        } else {
                            if (text.indexOf("${") == 0) {
                                bool = true;
                                var += text;
                            }

                            if (text.equals("}")) {
                                bool = false;

                                String a = "";
                                try {
                                    a = var.substring(2, var.length() - 1);
                                } catch (Exception e) {

                                }

                                Object valueobj = JSONToolsUtil.getValue(
                                        jsonObject, a, split);
                                String value = "";

                                if (valueobj != null) {
                                    value = valueobj.toString();
                                }

                                xwpfRun.setText(value, 0);

                                var = "";
                            } else {
                                if (bool) {
                                    xwpfRun.setText("", 0);
                                }
                            }
                        }
                    }
                }

            }

            List<XWPFTable> tables = new ArrayList<XWPFTable>();
            List<XWPFTableRow> tableRows = new ArrayList<XWPFTableRow>();
            List<XWPFTableCell> tableCells = new ArrayList<XWPFTableCell>();
            // 获取文档中的所有表格
            tables = docx.getTables();

            for (XWPFTable xwpfTable : tables) {
                List<JSONObject> jsonObjectsList = new ArrayList<JSONObject>();
                JSONObject objectJSON = new JSONObject();
                JSONArray strJSON = new JSONArray();
                JSONArray dataJSON = new JSONArray();

                // 获取表格的行对象
                tableRows = xwpfTable.getRows();

                for (XWPFTableRow xwpfTableRow : tableRows) {
                    // 获取表格的列对象
                    tableCells = xwpfTableRow.getTableCells();

                    Boolean bool = false; // 标记行是否是循环输入行
                    int pos = 0; // 标记索引位置
                    String dataString = "";

                    for (XWPFTableCell xwpfTableCell : tableCells) {
                        // 获取模板表格内容
                        String text = xwpfTableCell.getText();
                        if (text.indexOf("list@") >= 0) {
                            bool = true;
                            pos = tableRows.indexOf(xwpfTableRow);

                            List<String> stringsList = new ArrayList<String>();
                            // 获取替换对象
                            stringsList = this.getVarFromParagraph(text);

                            if (stringsList != null) {
                                for (String stringd : stringsList) {
                                    if (stringd.indexOf("list@") == 0) {
                                        String parm = stringd.substring(stringd
                                                .indexOf("#") + 1);
                                        dataString = stringd.substring(0,
                                                stringd.indexOf("#"));
                                        text = text.replace(stringd, parm);
                                    } else {
                                        String value = "";
                                        Object object = JSONToolsUtil.getValue(
                                                jsonObject, stringd, null);
                                        if (object != null) {
                                            value = object.toString();
                                        }
                                        text = text.replace("${" + stringd
                                                + "}", value);
                                    }
                                }
                            }

                            strJSON.add(text);
                        } else if (text.indexOf("NULL") >= 0) {
                            strJSON.add("");
                        }
                    }

                    if (bool) {
                        JSONArray array = new JSONArray();
                        array = JSONToolsUtil.getArray(jsonObject, dataString,
                                null);
                        if (array != null) {
                            dataJSON = array;
                            objectJSON.put("list", strJSON);
                            objectJSON.put("data", dataJSON);
                            objectJSON.put("pos", pos);
                            jsonObjectsList.add(objectJSON);

                            strJSON = new JSONArray();
                            dataJSON = new JSONArray();
                            objectJSON = new JSONObject();
                            pos = 0;
                        }
                    }

                }

                int indexpos = 0;
                for (int k = 0; k < jsonObjectsList.size(); k++) {
                    JSONObject objectSJSON = new JSONObject();
                    objectSJSON = jsonObjectsList.get(k);

                    if (objectSJSON.size() > 0) {
                        int pos = objectSJSON.getIntValue("pos");
                        pos += indexpos;
                        JSONArray strArr = new JSONArray();
                        strArr = objectSJSON.getJSONArray("list");
                        JSONArray dataArr = new JSONArray();
                        dataArr = objectSJSON.getJSONArray("data");

                        XWPFTableRow row = xwpfTable.getRow(pos);

                        List<XWPFTableCell> tableCells23 = row.getTableCells();
                        for (XWPFTableCell xwpfTableCellt : tableCells23) {
                            List<XWPFParagraph> paragraphs = xwpfTableCellt.getParagraphs();

                            for (XWPFParagraph xwpfParagraph : paragraphs) {
                                List<XWPFRun> runs = xwpfParagraph.getRuns();
                                for (XWPFRun xwpfRun : runs) {
                                    if (runs.lastIndexOf(xwpfRun) == (runs
                                            .size() - 1)) {
                                        xwpfRun.setText("", 0);
                                    } else {
                                        xwpfRun.setText("", 0);
                                    }
                                }
                            }
                        }

                        int size = 0;
                        size = dataArr.size();
                        indexpos = indexpos + size - 1;
                        if (size > 0) {
                            if (size > 1) {
                                for (int i = 0; i < size - 1; i++) {

                                    XWPFTableRow row2 = new XWPFTableRow(row.getCtRow(), xwpfTable);

                                    List<XWPFTableCell> tableCells2p = row2.getTableCells();

                                    int index = 0;
                                    for (XWPFTableCell xwpfTableCelld : tableCells2p) {
                                        String texts = "";
                                        try {
                                            texts = strArr.getString(index);
                                        } catch (Exception e) {
                                        }

                                        List<String> list = new ArrayList<String>();
                                        list = this.getVarFromParagraph(texts);

                                        JSONObject object = dataArr.getJSONObject(i);
                                        if (list != null) {
                                            for (String stringx : list) {
                                                String key = "";
                                                Object objectt = JSONToolsUtil
                                                        .getValue(object,
                                                                stringx, null);
                                                if (objectt != null) {
                                                    key = objectt.toString();
                                                }

                                                texts = texts.replace("${"
                                                        + stringx + "}", key);
                                            }
                                        }
                                        List<XWPFParagraph> paragraphs = xwpfTableCelld
                                                .getParagraphs();

                                        for (XWPFParagraph xwpfParagraph : paragraphs) {
                                            List<XWPFRun> runs = xwpfParagraph
                                                    .getRuns();
                                            for (XWPFRun xwpfRun : runs) {
                                                if (runs.lastIndexOf(xwpfRun) == (runs
                                                        .size() - 1)) {

                                                    // 文档替换
                                                    texts = replaceEnter(texts);
                                                    if (texts.contains("####")) {
                                                        xwpfRun.setText("", 0);
                                                        String[] testStr = texts.split("####");
                                                        for (String s : testStr) {
                                                            xwpfRun.setText("    " + s.trim());
                                                            xwpfRun.addBreak();
                                                        }
                                                    } else {
                                                        xwpfRun.setText(texts, 0);
                                                    }
                                                } else {
                                                    xwpfRun.setText("", 0);
                                                }
                                            }
                                        }
                                        index++;
                                    }

                                    xwpfTable.addRow(row2, pos + i);
                                }
                            }

                            XWPFTableRow row2 = new XWPFTableRow(
                                    row.getCtRow(), xwpfTable);

                            List<XWPFTableCell> tableCells2p = row2
                                    .getTableCells();

                            int index = 0;
                            for (XWPFTableCell xwpfTableCelld : tableCells2p) {
                                String texts = "";
                                try {
                                    texts = strArr.getString(index);
                                } catch (Exception e) {

                                }

                                List<String> list = new ArrayList<String>();
                                list = this.getVarFromParagraph(texts);

                                JSONObject object = dataArr.getJSONObject(size - 1);

                                if (list != null) {
                                    for (String stringx : list) {
                                        String key = "";
                                        Object objectt = JSONToolsUtil
                                                .getValue(object, stringx, null);
                                        if (objectt != null) {
                                            key = objectt.toString();
                                        }
                                        texts = texts.replace("${" + stringx
                                                + "}", key);
                                    }
                                }
                                List<XWPFParagraph> paragraphs = xwpfTableCelld
                                        .getParagraphs();

                                for (XWPFParagraph xwpfParagraph : paragraphs) {
                                    List<XWPFRun> runs = xwpfParagraph
                                            .getRuns();
                                    for (XWPFRun xwpfRun : runs) {
                                        if (runs.lastIndexOf(xwpfRun) == (runs
                                                .size() - 1)) {
                                            // 文档替换
                                            texts = replaceEnter(texts);
                                            if (texts.contains("####")) {
                                                xwpfRun.setText("", 0);
                                                String[] testStr = texts.split("####");
                                                for (String s : testStr) {
                                                    xwpfRun.setText("    " + s.trim());
                                                    xwpfRun.addBreak();
                                                }
                                            } else {
                                                xwpfRun.setText(texts, 0);
                                            }
                                        } else {
                                            xwpfRun.setText("", 0);
                                        }
                                    }
                                }
                                index++;
                            }
                        }

                    }

                }

                List<XWPFTableRow> tableRows2 = xwpfTable.getRows();

                for (XWPFTableRow xwpfTableRow2 : tableRows2) {
                    List<XWPFTableCell> tableCells2 = xwpfTableRow2
                            .getTableCells();

                    for (XWPFTableCell xwpfTableCell : tableCells2) {
                        String text = xwpfTableCell.getText();
                        List<String> stringsList = new ArrayList<String>();
                        // 获取替换对象
                        stringsList = this.getVarFromParagraph(text);
                        if (stringsList != null) {
                            // 解析并替换变量对象
                            for (String string : stringsList) {
                                String values = null;
                                Object obj = JSONToolsUtil.getValue(jsonObject,
                                        string, "@");
                                if (obj != null) {
                                    values = obj.toString();
                                }
                                if (values == null) {
                                    values = "";
                                }
                                text = text
                                        .replace("${" + string + "}", values);
                            }
                        }
                        List<XWPFParagraph> paragraphs = xwpfTableCell.getParagraphs();
                        for (XWPFParagraph xwpfParagraph : paragraphs) {
                            List<XWPFRun> runs = xwpfParagraph.getRuns();
                            for (XWPFRun xwpfRun : runs) {
                                if (runs.lastIndexOf(xwpfRun) == (runs.size() - 1)) {
                                    // 文档替换
                                    text = replaceEnter(text);
                                    if (text.contains("####")) {
                                        xwpfRun.setText("", 0);
                                        String[] testStr = text.split("####");
                                        for (String s : testStr) {
                                            xwpfRun.setText("    " + s.trim());
                                            xwpfRun.addBreak();
                                        }
                                    } else {
                                        xwpfRun.setText(text, 0);
                                    }
                                } else {
                                    xwpfRun.setText("", 0);
                                }
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return docx;
    }

    /**
     * 解析段落内容,获取变量值
     *
     * @param paragraphText
     * @return
     */
    public ArrayList<String> getVarFromParagraph(String paragraphText) {

        ArrayList<String> list = new ArrayList<String>();

        if (!paragraphText.contains("${")) {
            list = null;
        } else {
            paragraphText = paragraphText
                    .substring(paragraphText.indexOf("${"));
            while (paragraphText.indexOf("${") >= 0
                    && paragraphText.indexOf("}") > 1) {
                String keys = paragraphText.substring(
                        paragraphText.indexOf("${") + 2,
                        paragraphText.indexOf("}"));
                list.add(keys);
                paragraphText = paragraphText.substring(paragraphText
                        .indexOf("}") + 1);
            }
        }
        return list;
    }
public class DocumentReplaceUtil {
    
    /**
     * 替换工具
     *
     *
     * @param jsonObject 数据源
     * @param tempPath   模板地址 后缀.docx
     * @param source     true 从项目下读取模板地址
     * @return
     * @return
     */
    public static XWPFDocument getResultDocument(JSONObject jsonObject, String tempPath, boolean source) {
        DOCXDocument docxDocument = new DOCXDocument();
        InputStream ina = null;
        XWPFDocument docxApp = null;
        try {
            //不能使用这种方式,因为这种方式会获取jar包中的文件,报无法找到文件的错误
            if (source) {
                // 从工程jar包读取
                ina = XWPFDocument.class.getClassLoader().getResourceAsStream(tempPath);
            } else {
                // 从服务器读取
                ina = new FileInputStream(tempPath);
            }
            docxApp = new XWPFDocument(ina);
            docxApp = docxDocument.docxwrite(jsonObject, docxApp);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != ina) {
                try {
                    ina.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return docxApp;
    }

    /**
     * word内容替换方法
     *
     * @param jsonObject 数据源
     * @param tempPath   模板地址 后缀.docx
     * @param outPath    替换后文件地址.docx
     * @param source     true 从项目下读取模板地址
     * @return
     */
    public static boolean docxWrite(JSONObject jsonObject, String tempPath, String outPath, boolean source) {
        XWPFDocument xwpfDocument = getResultDocument(jsonObject, tempPath, source);
        if (null != xwpfDocument) {
            OutputStream os = null;
            try {
                os = new FileOutputStream(outPath);
            } catch (FileNotFoundException e) {
                return false;
            }
            try {
                xwpfDocument.write(os);
                return true;
            } catch (IOException e) {
                return false;
            }
        }
        return false;
    }
public class JSONToolsUtil {

    public static Object getResult(JSONObject objJSON, String string, String splitType) {
        if (splitType == null) {
            splitType = "@";
        }

        if (objJSON != null) {
            if (!string.contains(string)
                    || string.lastIndexOf(splitType) == string.length() - 1) {
                try {
                    return objJSON.getString(string);
                } catch (Exception e) {
                    return null;
                }
            } else {
                String[] str = string.split(splitType);
                /**
                 * 顺序解析json对象
                 */
                for (int i = 0; i < str.length - 1; i++) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject = objJSON.getJSONObject(str[i]);
                    } catch (Exception e) {
                        return null;
                    }
                    objJSON = jsonObject;
                }

                try {
                    return objJSON.getString(str[str.length - 1]);
                } catch (Exception e) {
                    return null;
                }
            }
        } else {
            return null;
        }
    }

    /**
     * 解析json,获取值
     *
     * @param objJSON   json对象
     * @param string    取值字符串
     * @param splitType 字符串分隔符类型
     * @return
     */
    public static Object getValue(JSONObject objJSON, String string, String splitType) {
        Object object = getResult(objJSON, string, splitType);
        if (null != object) {
            String d = object.toString();
            d = d.replace("\n", "");
            return d;
        }
        return null;

    }

    /**
     * 解析json,获取循环json数组对象
     *
     * @param jsonObject
     * @param string
     * @param splitType
     * @return
     */
    public static JSONArray getArray(JSONObject jsonObject, String string,
                                     String splitType) {
        JSONArray jsonArray = new JSONArray();
        String str = string.replaceAll(" ", "");

        if (splitType == null) {
            splitType = "@";
        }
        if (jsonObject != null) {
            if (str.indexOf("list@") != 0 || str.length() == 5) {
                jsonArray = null;
            } else {
                String[] strArray = string.split(splitType);
                int strLength = strArray.length;
                if (strLength == 2) {
                    try {
                        jsonArray = jsonObject.getJSONArray(strArray[1]);
                    } catch (Exception e) {
                        jsonArray = null;
                    }
                } else if (strLength > 2) {
                    JSONObject jsonObj = new JSONObject();
                    jsonObj = jsonObject;
                    for (int i = 1; i < strArray.length - 1; i++) {
                        try {
                            jsonObj = jsonObj.getJSONObject(strArray[i]);
                        } catch (Exception e) {
                            jsonObj = null;
                        }
                    }

                    if (jsonObj != null) {
                        try {
                            jsonArray = jsonObj
                                    .getJSONArray(strArray[strLength - 1]);
                        } catch (Exception e) {
                            jsonArray = null;
                        }
                    }

                } else {
                    jsonArray = null;
                }
            }
        } else {
            jsonArray = null;
        }
        return jsonArray;
    }

}
public static void main(String[] args) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("student_number", "B001");
        jsonObject.put("student_name", "张三");
        JSONArray jsonArray = new JSONArray();
        JSONObject jo = new JSONObject();
        jo.put("name", "计算机");
        jo.put("score", "5");
        jsonArray.add(jo);
        JSONObject jo1 = new JSONObject();
        jo1.put("name", "高数");
        jo1.put("score", "2");
        jsonArray.add(jo1);
        jsonObject.put("course", jsonArray);
        String filePath = "D:\\xx.docx";
        XWPFDocument xwpfDocument = getResultDocument(jsonObject, filePath, false);
        if (null != xwpfDocument) {
            String str = "D:\\"+ IdUtil.simpleUUID() + ".docx";
            OutputStream os = new FileOutputStream(str);
            xwpfDocument.write(os);
        }
    }

替换后word
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值