Word自定义文件生成及Word填充

本文介绍了如何使用Java的ApachePOI库中的XWPFDocument类创建和编辑Word文档,包括创建标题、段落、设置样式,并展示了如何填充带有占位符的模板。
摘要由CSDN通过智能技术生成
    @Test
    public void word() throws IOException {
        // 创建一个空白文档
        XWPFDocument doc = new XWPFDocument();
        DpItem dpItem = dpItemMapper.selByItemId(55L);
        dpItem.setRemark("1");

        if (dpItem.getItemName() != null) {

            // 创建一个居中对齐的标题段落
            XWPFParagraph titleParagraph = doc.createParagraph();
            titleParagraph.setAlignment(ParagraphAlignment.CENTER);

            // 创建标题运行
            XWPFRun titleRun = titleParagraph.createRun();
            titleRun.setText(dpItem.getItemName());
            titleRun.setFontFamily("宋体");  // 设置字体
            titleRun.setFontSize(26);      // 设置字号
            titleRun.setBold(true);        // 设置为粗体
            titleRun.setColor("000000");   // 设置文本颜色

            // 添加段前段后行距,使标题与其他内容有一定的间距
            titleParagraph.setSpacingBeforeLines(60);
            titleParagraph.setSpacingAfterLines(60);
        }


        if (dpItem.getItemIntroduce() != null) {
//
            // 添加第一个段落
            XWPFParagraph para2 = doc.createParagraph();
            setFirstLineIndent(para2, 600); // 设置首行缩进为600
            para2.setSpacingBetween(1, LineSpacingRule.AUTO); // 设置行距为1磅
            para2.setAlignment(ParagraphAlignment.BOTH); // 设置段落对齐方式为两端对齐
            XWPFRun run2 = para2.createRun();
            run2.setText(dpItem.getItemIntroduce());
            run2.setFontFamily("等线 (西文正文)"); // 设置字体名称为"Arial"
            run2.setFontSize(12); // 设置字体大小为12
        }
        if (dpItem.getItemExamine() != null) {
            // 添加第二个段落
            XWPFParagraph para3 = doc.createParagraph();
            setFirstLineIndent(para3, 700); // 设置首行缩进为700
            XWPFRun run3 = para3.createRun();
            run3.setText(dpItem.getItemExamine());
            run3.setFontFamily("等线 (西文正文)"); // 设置字体名称为"Times New Roman"
            run3.setFontSize(12); // 设置字体大小为12
        }

        if (dpItem.getItemSituation() != null) {

            // 添加第三个段落
            XWPFParagraph para3 = doc.createParagraph();
            setFirstLineIndent(para3, 700); // 设置首行缩进为700
            XWPFRun run3 = para3.createRun();
            run3.setText(dpItem.getItemSituation());
            run3.setFontFamily("等线 (西文正文)"); // 设置字体名称
            run3.setFontSize(12); // 设置字体大小为12
        }

        if (dpItem.getItemInvestment() != null) {
            // 添加第三个段落
            XWPFParagraph para3 = doc.createParagraph();
            setFirstLineIndent(para3, 700); // 设置首行缩进为700
            XWPFRun run3 = para3.createRun();
            run3.setText(dpItem.getItemInvestment());
            run3.setFontFamily("等线 (西文正文)"); // 设置字体名称
            run3.setFontSize(12); // 设置字体大小为16磅
        }

        // 保存文档到文件
        try (FileOutputStream out = new FileOutputStream("C://Users//Shi//Desktop//" + dpItem.getItemName() + ".docx")) {
            doc.write(out);
        }


    }

    /**
     * 设置段落的首行缩进
     *
     * @param paragraph 段落对象
     * @param indent    首行缩进的大小(磅)
     */
    private static void setFirstLineIndent(XWPFParagraph paragraph, int indent) {
        CTPPr ppr = paragraph.getCTP().getPPr();
        if (ppr == null)
            ppr = paragraph.getCTP().addNewPPr();

        CTInd ctInd = ppr.isSetInd() ? ppr.getInd() : ppr.addNewInd();
        ctInd.setFirstLine(BigInteger.valueOf(indent));
    }


    /**
     * word模板填充
     */
    @Test
    public void fill() {
        String templatePath = "C://Users//Shi//Desktop//测试项目名称1。1.docx";
        String outputPath = "C://Users//Shi//Desktop//测试项目名称1.docx";

        Map<String, RunStyle> placeholderMap = new HashMap<>();
        placeholderMap.put("{{NAME}}", new RunStyle("Arial", true, "FF0000"));
        placeholderMap.put("{{EMAIL}}", new RunStyle("Times New Roman", false, "0000FF"));
        // 添加更多的占位符、样式

        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("{{NAME}}", "John Doe");
        contentMap.put("{{EMAIL}}", "johndoe@example.com");
        // 添加更多的占位符、内容

        try (FileInputStream fis = new FileInputStream(templatePath);
             FileOutputStream fos = new FileOutputStream(outputPath)) {
            XWPFDocument document = new XWPFDocument(fis);

            for (XWPFParagraph paragraph : document.getParagraphs()) {
                replacePlaceholders(paragraph, placeholderMap, contentMap);
            }

            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph paragraph : cell.getParagraphs()) {
                            replacePlaceholders(paragraph, placeholderMap, contentMap);
                        }
                    }
                }
            }

            document.write(fos);
            System.out.println("Word 模板填充完成!");
        } catch (Exception e) {
            System.out.println("发生异常:" + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void replacePlaceholders(XWPFParagraph paragraph, Map<String, RunStyle> placeholderMap,
                                            Map<String, String> contentMap) {
        for (XWPFRun run : paragraph.getRuns()) {
            String text = run.getText(0);
            if (text != null) {
                for (Map.Entry<String, RunStyle> entry : placeholderMap.entrySet()) {
                    if (text.contains(entry.getKey())) {
                        // 应用样式
                        RunStyle style = entry.getValue();
                        CTRPr ctrPr = run.getCTR().getRPr();
                        if (ctrPr == null) {
                            ctrPr = run.getCTR().addNewRPr();
                        }
                        CTFonts fonts = ctrPr.isSetRFonts() ? ctrPr.getRFonts() : ctrPr.addNewRFonts();
                        fonts.setAscii(style.font);  // 设置字体
                        fonts.setHAnsi(style.font);
                        if (style.bold) {
                            ctrPr.addNewB();  // 加粗文本
                        }
                        if (style.color != null) {
                            ctrPr.addNewColor().setVal(style.color);  // 设置文本颜色
                        }

                        // 替换占位符
                        text = text.replace(entry.getKey(), contentMap.get(entry.getKey()));
                        run.setText(text, 0);
                    }
                }
            }
        }
    }

    // 定义样式类型
    static class RunStyle {
        String font;   // 字体
        boolean bold;  // 是否加粗
        String color;  // 颜色

        public RunStyle(String font, boolean bold, String color) {
            this.font = font;
            this.bold = bold;
            this.color = color;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值