多个word文档合并为一个文档 Java实现

不用额外新建一个空文档,适合需要不断往一个文档中添加其他文档的情况。适合每页格式固定,添加文件新起一页的情况。可进行测试。

package could.com.hanwen.govapi.Test;

import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.BreakType;
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;

public class FileCopyUtil {
   public void aqscMergeDoc(String outPutPath, String mergeWord) {

		List<File> srcfile = new ArrayList<>();
		File file1 = new File(outPutPath);
		File file2 = new File(mergeWord);
		srcfile.add(file1);
		srcfile.add(file2);

		try {
			ArrayList<XWPFDocument> documentList = new ArrayList<>();
			for (int i = 0; i < srcfile.size(); i++) {
				FileInputStream in = new FileInputStream(srcfile.get(i).getPath());
				OPCPackage open = OPCPackage.open(in);
				XWPFDocument document = new XWPFDocument(open);
				documentList.add(document);
			}
			XWPFDocument doc = documentList.get(0);
			if (CollectionUtils.isEmpty(documentList)) {
				throw  new RuntimeException("待合并的word文档list为空");
			}
			int size = documentList.size();
			if (size > 1) {
				doc.createParagraph().setPageBreak(true);
				for (int i = 1; i < size; i++) {
					// 从第二个word开始合并
					XWPFDocument nextPageDoc = documentList.get(i);
					// 最后一页不需要设置分页符
					if (i != (size-1)) {
						nextPageDoc.createParagraph().setPageBreak(true);
					}
					appendBody(doc, nextPageDoc);
				}
			}
			new File(outPutPath).delete();
			OutputStream dest = new FileOutputStream(outPutPath);
			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);
        }
        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 rgex = "<[\\s]*?w:sectPr[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?w:sectPr[\\s]*?>";
        appendString = appendString.replaceAll(rgex, "");
        String srcString = src.xmlText();
        String prefix = srcString.substring(0, srcString.indexOf(">"));
        String mainPart = srcString.substring(srcString.indexOf(">"), srcString.lastIndexOf("<"));
        String sufix = srcString.substring(srcString.lastIndexOf("<"));
        String addPart = appendString.substring(appendString.indexOf(">"), appendString.lastIndexOf("<"));
        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);
    }

    /*public static void main(String[] args) {
        List<File> srcfile = new ArrayList<>();
        File file1 = new File("F:\\安全生产责任制度.docx");
        File file2 = new File("F:\\安全生产责任制度新增.docx");
        srcfile.add(file1);
        srcfile.add(file2);
        try {
            ArrayList<XWPFDocument> documentList = new ArrayList<>();
            for (int i = 0; i < srcfile.size(); i++) {
                FileInputStream in = new FileInputStream(srcfile.get(i).getPath());
                OPCPackage open = OPCPackage.open(in);
                XWPFDocument document = new XWPFDocument(open);
                documentList.add(document);
            }
            XWPFDocument doc = documentList.get(0);
            if (CollectionUtils.isEmpty(documentList)) {
                throw  new RuntimeException("待合并的word文档list为空");
            }
            int size = documentList.size();
            if (size > 1) {
                doc.createParagraph().setPageBreak(true);
                for (int i = 1; i < size; i++) {
                    // 从第二个word开始合并
                    XWPFDocument nextPageDoc = documentList.get(i);
                    // 最后一页不需要设置分页符
                    if (i != (size-1)) {
                        nextPageDoc.createParagraph().setPageBreak(true);
                    }
                    appendBody(doc, nextPageDoc);
                }
            }

            new File("F:\\安全生产责任制度.docx").delete();
            OutputStream dest = new FileOutputStream("F:\\安全生产责任制度.docx");
            doc.write(dest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}

如果希望添加的文档直接接在上一文档末尾将srcString替换:

		// 去除分页符
		String srcString = src.xmlText().replaceAll( "<w:p><w:r><w:br w:type=\"page\"/></w:r></w:p>", "" ).replaceAll( "<w:r><w:br w:type=\"page\"/></w:r>", "" );

参考资料:
1、http://t.zoukankan.com/zeng1994-p-bef8f7ab14486d489db8ee72b9f8ffc0.html

2、合并格式、去掉分页符

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java合并多个Word文档可以通过使用Apache POI库来实现。POI(Poor Obfuscation Implementation)是一个用于操作各种Microsoft Office文件格式的开源Java库。 首先,我们需要在项目中导入POI库的依赖。可以通过添加以下Maven依赖来实现: ```xml <dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> </dependencies> ``` 然后,我们可以编写代码来合并多个Word文档。首先,我们创建一个空白的文档,作为目标文档: ```java import org.apache.poi.xwpf.usermodel.*; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; public class WordDocumentMerger { public static void main(String[] args) { try { XWPFDocument mergedDocument = new XWPFDocument(); // 读取需要合并多个文档 List<String> fileNames = List.of("document1.docx", "document2.docx", "document3.docx"); for (String fileName : fileNames) { FileInputStream fis = new FileInputStream(fileName); XWPFDocument document = new XWPFDocument(fis); // 将每个文档的内容复制到目标文档 for (IBodyElement element : document.getBodyElements()) { if (element instanceof XWPFParagraph) { mergedDocument.createParagraph().createRun().setText(((XWPFParagraph) element).getText()); } else if (element instanceof XWPFTable) { mergedDocument.createTable().addNewRow().getCell(0) .setText(((XWPFTable) element).getText()); } } fis.close(); } // 保存合并后的文档 FileOutputStream fos = new FileOutputStream("merged_document.docx"); mergedDocument.write(fos); fos.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 这个例子读取了名为`document1.docx`、`document2.docx`和`document3.docx`的三个文档,并将它们的内容复制到一个新的`merged_document.docx`文档中。 需要注意的是,POI库只能合并文档的内容,而不包括格式和样式。如果需要合并格式和样式,请使用其他第三方库或者Microsoft Office本身的API。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值