Java使用POI合并word

调用方法前需要提前导入poi的maven依赖。

这个方法可以实现每个word前自定义标题以及合并文字、图片、表格、样式、目录...

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        try {
            //自行替换文件路径
            List<String> list = new ArrayList<>();
            list.add("需要合并的doc路径");
            list.add("需要合并的doc1路径");
            String fileName = "最终版本的doc路径";
            CustomXWPFDocument destDoc = new CustomXWPFDocument();
            FileOutputStream out = new FileOutputStream(fileName);

            for (String s : list) {
                // 创建段落对象
                XWPFParagraph paragraph = destDoc.createParagraph();
                XWPFRun run = paragraph.createRun();
                run.setText("自定义标题:");
                run.setBold(true);
                run.setFontSize(20);
                XWPFDocument content = getWordContent(s);
                for (IBodyElement bodyElement : content.getBodyElements()) {
                    boolean hasImage = false;
                    BodyElementType elementType = bodyElement.getElementType();
                    if (elementType == BodyElementType.PARAGRAPH) {
                        //文字
                        XWPFParagraph srcPr = (XWPFParagraph) bodyElement;
                        //复制样式
                        copyStyle(content, destDoc, content.getStyles().getStyle(srcPr.getStyleID()));
                        XWPFParagraph destPr = destDoc.createParagraph();
                        for (XWPFRun srcPrRun : srcPr.getRuns()) {
                            XWPFRun run1 = destPr.createRun();
                            run1.setText(srcPrRun.text());
                            if (srcPrRun.getEmbeddedPictures().size() > 0) {
                                hasImage = true;
                            }
                            for (XWPFPicture pic : srcPrRun.getEmbeddedPictures()) {
                                byte[] img = pic.getPictureData().getData();
                                long cx = pic.getCTPicture().getSpPr().getXfrm().getExt().getCx();
                                long cy = pic.getCTPicture().getSpPr().getXfrm().getExt().getCy();
                                try {
                                    // Working addPicture Code below...
                                    String blipId = destPr.getDocument().addPictureData(new ByteArrayInputStream(img), Document.PICTURE_TYPE_PNG);
                                    destDoc.createPictureCxCy(blipId, destDoc.getNextPicNameNumber(Document.PICTURE_TYPE_PNG), cx, cy);
                                } catch (InvalidFormatException e1) {
                                    e1.printStackTrace();
                                }
                            }
                        }
                        if (hasImage == false) {
                            int pos = destDoc.getParagraphs().size() - 1;
                            destDoc.setParagraph(srcPr, pos);
                        }
                    }else if (elementType == BodyElementType.TABLE) {
                        XWPFTable table = (XWPFTable) bodyElement;
                        destDoc.createTable();
                        int pos = destDoc.getTables().size() - 1;
                        destDoc.setTable(pos, table);
                    }
                }
            }
            destDoc.write(out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文档
     *
     * @param filePath
     * @return
     */
    public static XWPFDocument getWordContent(String filePath) {
        File file = new File(filePath);
        try (FileInputStream fis = new FileInputStream(file)) {
            XWPFDocument document = new XWPFDocument(fis);
            return document;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static void copyStyle(XWPFDocument srcDoc, XWPFDocument destDoc, XWPFStyle style) {
        if (destDoc == null || style == null) return;
        if (destDoc.getStyles() == null) {
            destDoc.createStyles();
        }
        List<XWPFStyle> usedStyleList = srcDoc.getStyles().getUsedStyleList(style);
        for (XWPFStyle xwpfStyle : usedStyleList) {
            destDoc.getStyles().addStyle(xwpfStyle);
        }
    }
}
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;

import java.io.IOException;

public class CustomXWPFDocument extends XWPFDocument {
    public CustomXWPFDocument() throws IOException
    {
        super();
    }

    public void createPictureCxCy(String blipId,int id, long cx, long cy)
    {
        CTInline inline = createParagraph().createRun().getCTR().addNewDrawing().addNewInline();

        String picXml = "" +
                "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" +
                " <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
                "  <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
                "   <pic:nvPicPr>" +
                "   <pic:cNvPr id=\"" + id + "\" name=\"Generated\"/>" +
                "   <pic:cNvPicPr/>" +
                "   </pic:nvPicPr>" +
                "   <pic:blipFill>" +
                "   <a:blip r:embed=\"" + blipId + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" +
                "   <a:stretch>" +
                "    <a:fillRect/>" +
                "   </a:stretch>" +
                "   </pic:blipFill>" +
                "   <pic:spPr>" +
                "   <a:xfrm>" +
                "    <a:off x=\"0\" y=\"0\"/>" +
                "    <a:ext cx=\"" + cx + "\" cy=\"" + cy + "\"/>" +
                "   </a:xfrm>" +
                "   <a:prstGeom prst=\"rect\">" +
                "    <a:avLst/>" +
                "   </a:prstGeom>" +
                "   </pic:spPr>" +
                "  </pic:pic>" +
                " </a:graphicData>" +
                "</a:graphic>";

        //CTGraphicalObjectData graphicData = inline.addNewGraphic().addNewGraphicData();
        XmlToken xmlToken = null;
        try
        {
            xmlToken = XmlToken.Factory.parse(picXml);
        }
        catch(XmlException xe)
        {
            xe.printStackTrace();
        }
        inline.set(xmlToken);
        //graphicData.set(xmlToken);

        inline.setDistT(0);
        inline.setDistB(0);
        inline.setDistL(0);
        inline.setDistR(0);

        CTPositiveSize2D extent = inline.addNewExtent();
        extent.setCx(cx);
        extent.setCy(cy);

        CTNonVisualDrawingProps docPr = inline.addNewDocPr();
        docPr.setId(id);
        docPr.setName("Picture " + id);
        docPr.setDescr("Generated");
    }

    public void createPicture(String blipId,int id, int width, int height)
    {
        final int EMU = 9525;
        width *= EMU;
        height *= EMU;
        //String blipId = getAllPictures().get(id).getPackageRelationship().getId();

        createPictureCxCy(blipId, id, width, height);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
使用JavaPOI库可以拼接Word文档。POI是Apache开发的用于操作Office文档的Java库,可以通过POI的XWPF模块来处理Word文档。 首先,我们需要创建一个XWPFDocument对象,该对象代表了一个空白的Word文档。然后我们可以像操作文本一样,通过调用XWPFDocument的方法来添加文本、表格、图片等内容到文档中。 例如,我们可以通过调用XWPFDocument的createParagraph()方法来创建一个段落,然后再调用段落对象的createRun()方法来创建一个文本运行,最后调用文本运行对象的setText()方法来设置文本内容。 如果想要添加表格,可以通过调用XWPFDocument的createTable()方法来创建一个表格对象,然后再通过调用表格对象的createRow()方法来创建行对象,并调用行对象的createCell()方法来创建单元格对象,最后通过调用单元格对象的setText()方法来设置单元格内容。 在将多个Word文档拼接为一个文件时,我们可以创建多个XWPFDocument对象,然后通过调用XWPFDocument的merge()方法来将它们合并成一个文档。合并后的文档可以保存到本地文件或者输出到流中。 最后,记得在使用完毕后关闭XWPFDocument对象,以释放资源。 总结来说,使用JavaPOI库实现拼接Word文档的流程大致如上所述。通过调用XWPFDocument的各种方法来操作文档对象,最后合并文档并保存。这样就可以实现使用Java拼接Word文档的功能了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱代码的小郭

请留下一点心意

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值