在这里面doc该怎么存储文件啊,然后Range怎么在里面插入信息啊,该怎么把Range像XWPFDocument他一样

请问下,在这里面doc该怎么存储文件啊,然后Range怎么在里面插入信息啊,该怎么把Range像XWPFDocument他一样,放入集合中。


 
package com.common.utils;
 
 
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * @Author mischen
 * @Description 文件合并 只支持.docx
 * @Date 2022/11/21 16:30
 * @Version 1.0
 */
public class DocxMerge {
    public static void main(String[] args) {
        File file1 = new File("F:\\test1\\3.docx");
        List<File> targetFile1 = new ArrayList<>();
        targetFile1.add(new File("F:\\test1\\a.docx"));
        targetFile1.add(new File("F:\\test1\\01-系统架构设计师教程(第4版)_划了重点.docx"));
 
        appendDocx(file1, targetFile1);
        System.out.println("合并成功!!!");
    }
 
    /**
     * 把多个docx文件合并成一个
     *
     * @param outfile    输出文件
     * @param targetFile 目标文件
     */
    public static void appendDocx(File outfile, List<File> targetFile) {
        try {
 
            OutputStream dest = new FileOutputStream(outfile);
            ArrayList<XWPFDocument> documentList = new ArrayList<>();
            XWPFDocument doc = null;
            for (int i = 0; i < targetFile.size(); i++) {
                ZipSecureFile.setMinInflateRatio(-1.0d);
                FileInputStream in = new FileInputStream(targetFile.get(i).getPath());
                OPCPackage open = OPCPackage.open(in);
                XWPFDocument document = new XWPFDocument(open);
                documentList.add(document);
            }
            for (int i = 0; i < documentList.size(); i++) {
                doc = documentList.get(0);
                if (i != 0) {
                    //解决word合并完后,所有表格都紧紧挨在一起,没有分页。加上了分页符可解决
                    documentList.get(i).createParagraph().setPageBreak(true);
                    appendBody(doc, documentList.get(i));
                }
            }
 
            doc.write(dest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static void appendBody(XWPFDocument src, XWPFDocument append) throws Exception {
        CTBody src1Body = src.getDocument().getBody();
        CTBody src2Body = append.getDocument().getBody();
 
        List<XWPFPictureData> allPictures = append.getAllPictures();
        // 记录图片合并前及合并后的ID
        Map<String, String> map = new HashMap<>();
        for (XWPFPictureData picture : allPictures) {
            String before = append.getRelationId(picture);
            //将原文档中的图片加入到目标文档中
            String after = src.addPictureData(picture.getData(), Document.PICTURE_TYPE_PNG);
            map.put(before, after);
        }
        //这个代码主要解决合并word报错,解析抛出压缩炸弹
        ZipSecureFile.setMinInflateRatio(-1.0d);
        appendBody(src1Body, src2Body, map);
 
    }
 
    private static void appendBody(CTBody src, CTBody append, Map<String, String> map) throws Exception {
        XmlOptions optionsOuter = new XmlOptions();
        optionsOuter.setSaveOuter();
        String appendString = append.xmlText(optionsOuter);
 
        String srcString = src.xmlText();
        String prefix = srcString.substring(0, srcString.indexOf(">") + 1);
        String mainPart = srcString.substring(srcString.indexOf(">") + 1, srcString.lastIndexOf("<"));
        String sufix = srcString.substring(srcString.lastIndexOf("<"));
        String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
        //下面这部分可以去掉,我加上的原因是合并的时候,有时候出现打不开的情况,对照document.xml将某些标签去掉就可以正常打开了
        addPart = addPart.replaceAll("w14:paraId=\"[A-Za-z0-9]{1,10}\"", "");
        addPart = addPart.replaceAll("w14:textId=\"[A-Za-z0-9]{1,10}\"", "");
        addPart = addPart.replaceAll("w:rsidP=\"[A-Za-z0-9]{1,10}\"", "");
        addPart = addPart.replaceAll("w:rsidRPr=\"[A-Za-z0-9]{1,10}\"", "");
        addPart = addPart.replace("<w:headerReference r:id=\"rId8\" w:type=\"default\"/>","");
        addPart = addPart.replace("<w:footerReference r:id=\"rId9\" w:type=\"default\"/>","");
        addPart = addPart.replace("xsi:nil=\"true\"","");
 
        if (map != null && !map.isEmpty()) {
            //对xml字符串中图片ID进行替换
            for (Map.Entry<String, String> set : map.entrySet()) {
                addPart = addPart.replace(set.getKey(), set.getValue());
            }
        }
        //将两个文档的xml内容进行拼接
        CTBody makeBody = CTBody.Factory.parse(prefix + mainPart + addPart + sufix);
 
        src.set(makeBody);
    }
}
 
 
 

存储文件可以使用File对象或者ByteArrayOutputStream对象。
Range对象可以添加到XWPFDocument对象中, Steps:

  1. 创建XWPFDocument对象从docx文件中
    java
    XWPFDocument document = new XWPFDocument(OPCPackage.open("source.docx"));
  2. 使用document获取body元素
    java
    XWPFBody body = document.getBody();
  3. 向body中添加paragraph
    java
    XWPFParagraph paragraph = body.addParagraph();
  4. 向paragraph中添加Run对象(代表文字内容)
    java
    XWPFRun run = paragraph.addRun();
    run.setText("Some text");
  5. 可以向Run对象设置各种属性,如字体,颜色,下划线等
    java
    run.setBold(true);
    run.setColor("0000FF");
    run.setUnderline(UnderlinePatterns.SINGLE);
  6. 最后使用输出流将修改后的document对象写入文件
    java
    FileOutputStream out = new FileOutputStream("destination.docx");
    document.write(out);
    out.close();
    所以,总结步骤就是:
  7. 读取docx文件为XWPFDocument对象
  8. 获取body元素
  9. 向body中添加paragraph
  10. 向paragraph中添加Run对象并设置属性
  11. 将XWPFDocument对象写入文件
    这样Range(Run)对象就被添加到了XWPFDocument中,实现了文档修改的效果。