Java Word文档模板内容替换

Apache POI

  • 可处理docx,xlsx,pptx,visio等文件
  • 纯Java工具包,无需第三方依赖
  • 主要类
  • XWPDFDocument 整个文档对象
  • XWPFParagraph 段落
  • XWPFRun 一个片段(字体样式相同的一段)
  • XWPFPicture 图片
  • XWPFTable 表格

Maven导入POI

<dependencies>
    <dependency>
        <groupId>org.apache.poigroupId>
        <artifactId>poiartifactId>
        <version>3.17version>
    dependency>
    <dependency>
        <groupId>org.apache.poigroupId>
        <artifactId>poi-ooxmlartifactId>
        <version>3.17version>
    dependency>
dependencies>

代码实现

public class Demo7 {
    public static void main(String[] args) throws Exception {
        // 导入文档模板
        XWPFDocument doc = openDocx("C:\\Users\\Wong\\Desktop\\test.docx");
        if (doc != null) {
            // 文本类 key-value
            Map<String, Object> params = new HashMap<>();
            params.put("${name}", "Tang");
            params.put("${sex}", "男");
            // 图片类 key-url
            Map<String, String> picParams = new HashMap<>();
            picParams.put("${pic}", "C:\\Users\\Wong\\Desktop\\新建文件夹\\style1.jpg");

            // 获取文档对象所有子元素
            List<IBodyElement> ibs = doc.getBodyElements();
            for (IBodyElement ib : ibs) {
                // 读取的文档对象类型判断是否是表格
                if (ib.getElementType() == BodyElementType.TABLE) {
                    // 替换表格
                    replaceTable(ib, params, picParams, doc);
                }
            }
            // 输出文档
            writeDocx(doc, new FileOutputStream("C:\\Users\\Wong\\Desktop\\test1.docx"));
        } else {
            System.out.println("文档对象为空");
        }
    }

    /**
     * @param ib           文档中的子元素
     * @param params       文档模板中的参数
     * @param picParams    图片参数
     * @param doc          文档对象
     * @return void
     * */
    private static void replaceTable(IBodyElement ib, Map<String, Object> params, Map<String, String> picParams, XWPFDocument doc) throws Exception {
        Matcher matcher;
        XWPFTable table;
        List<XWPFTableRow> rows;
        List<XWPFTableCell> cells;
        table = (XWPFTable) ib;
        // 获取表格的每一行
        rows = table.getRows();

        for (XWPFTableRow row : rows) {
            // 获取表格的每一列
            cells = row.getTableCells();
            int cellsize = cells.size();
            int cellcount = 0;

            for (cellcount = 0; cellcount < cellsize; cellcount++) {
                XWPFTableCell cell = cells.get(cellcount);
                String runtext = "";
                // 获取单元格的段落内容
                List<XWPFParagraph> ps = cell.getParagraphs();

                for (XWPFParagraph p : ps) {

                    // 获取每个段落的片段(字体样式相同的一段)
                    for (XWPFRun run : p.getRuns()) {
                        // 获取片段中的文本
                        runtext = run.text();
                        // 匹配${}中的内容
                        matcher = matcher(runtext);
                        if (matcher.find()) {
                            // picParams不为null则说明用户需要插入图片
                            if (picParams != null) {

                                for (String picKey : picParams.keySet()) {
                                    if (matcher.group().equals(picKey)) {
                                        run.setText("", 0);
                                        // 替换图片
                                        replacePic(run, picParams.get(picKey), doc);
                                    }
                                }

                            }

                            // 替换文本
                            if (params != null) {
                                for (String picKey : params.keySet()) {
                                    if (matcher.group().equals(picKey)) {
                                        run.setText(params.get(picKey) + "", 0);
                                    }
                                }

                            }

                        }
                    }

                }

            }

        }
    }

    /**
     * 写入image
     * @param run        需要替换图片的片段
     * @param imgFile    图片路径
     * @param doc        文档对象
     * @throws Exception
     */
    public static void replacePic(XWPFRun run,  String imgFile,  XWPFDocument doc) throws Exception {
        int format;
        if (imgFile.endsWith(".emf"))
            format = Document.PICTURE_TYPE_EMF;
        else if (imgFile.endsWith(".wmf"))
            format = Document.PICTURE_TYPE_WMF;
        else if (imgFile.endsWith(".pict"))
            format = Document.PICTURE_TYPE_PICT;
        else if (imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg"))
            format = Document.PICTURE_TYPE_JPEG;
        else if (imgFile.endsWith(".png"))
            format = Document.PICTURE_TYPE_PNG;
        else if (imgFile.endsWith(".dib"))
            format = Document.PICTURE_TYPE_DIB;
        else if (imgFile.endsWith(".gif"))
            format = Document.PICTURE_TYPE_GIF;
        else if (imgFile.endsWith(".tiff"))
            format = Document.PICTURE_TYPE_TIFF;
        else if (imgFile.endsWith(".eps"))
            format = Document.PICTURE_TYPE_EPS;
        else if (imgFile.endsWith(".bmp"))
            format = Document.PICTURE_TYPE_BMP;
        else if (imgFile.endsWith(".wpg"))
            format = Document.PICTURE_TYPE_WPG;
        else {
            System.err.println(
                    "Unsupported picture: " + imgFile + ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
            return;
        }
        if(imgFile.startsWith("http")||imgFile.startsWith("https")){
            run.addPicture(new URL(imgFile).openConnection().getInputStream(), format, "rpic",Units.toEMU(100),Units.toEMU(100));
        }else{
            run.addPicture(new FileInputStream(imgFile), format, "rpic", Units.toEMU(100),Units.toEMU(100));
        }
    }

    /**
     * @param runtext    匹配${}中的内容
     * @return Matcher   匹配结果
     * */
    private static Matcher matcher(String runtext) {
        Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(runtext);
        return matcher;
    }

    /**
     * @param url             获取文档对象的路径
     * @return XWPFDocument   返回文档对象
     * */
    public static XWPFDocument openDocx(String url) {
        XWPFDocument doc = null;
        try (InputStream input = new FileInputStream(url)) {
                doc = new XWPFDocument(input);
                return doc;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return doc;
    }

    /**
     * @param outDoc    输出的文档对象
     * @param out       输出内容
     * @return void
     * */
    public static void writeDocx(XWPFDocument outDoc, OutputStream out) {
        try {
            outDoc.write(out);
            out.flush();
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
文档模板

Java Word文档模板内容替换_第1张图片

内容替换

Java Word文档模板内容替换_第2张图片

你可能感兴趣的:(JAVA,poi,正则表达式,dom)