一、需求说明

例如将封面插入到word正文上方

二、导入依赖

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi</artifactId>
  4. <version>4.1.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.poi</groupId>
  8. <artifactId>poi-ooxml</artifactId>
  9. <version>4.1.1</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.apache.poi</groupId>
  13. <artifactId>poi-ooxml-schemas</artifactId>
  14. <version>4.1.1</version>
  15. </dependency>
  16.  
  17. <dependency>
  18. <groupId>org.apache.xmlbeans</groupId>
  19. <artifactId>xmlbeans</artifactId>
  20. <version>3.1.0</version>
  21. </dependency>

三、准备工作

准备两个word文档

四、代码

  1. import java.io.File;
  2. import java.io.FileFilter;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.OutputStream;
  6. import java.util.ArrayList;
  7. import java.util.HashMap;
  8. import java.util.List;
  9. import java.util.Map;
  10. import org.apache.poi.openxml4j.opc.OPCPackage;
  11. import org.apache.poi.xwpf.usermodel.Document;
  12. import org.apache.poi.xwpf.usermodel.XWPFDocument;
  13. import org.apache.poi.xwpf.usermodel.XWPFPictureData;
  14. import org.apache.xmlbeans.XmlOptions;
  15. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
  16.  
  17. public class test {
  18. public static void main (String[] args) throws Exception {
  19.  
  20. /*String[] str = {"街道(年度)","街道(季度)","街道(月度)","全区(年度)","全区(季度)","全区(月度)"};*/
  21. String[] str = {"街道(年度)"};
  22. for (int k = 0; k < str.length; k++) {
  23. String type = str[k];
  24. String path ="E:/1/确认打印报告/"+type+"/";
  25. File fileRoot = new File(path);
  26. List<File> subFileList = new ArrayList<File>();
  27. getAllFile(subFileList,fileRoot);
  28. for (File file : subFileList) {
  29. String name = file.getName();
  30. File newFile = new File("f:/final/"+type+"/"+name);
  31. List<File> srcfile = new ArrayList<>();
  32. File file1 = new File("E:/1/确认打印报告/"+type+"/"+name);
  33. File file2 = new File("D:/word/封面/生成/"+type+"/"+name);
  34.  
  35. srcfile.add(file1);
  36. srcfile.add(file2);
  37.  
  38. try {
  39. OutputStream dest = new FileOutputStream(newFile);
  40. ArrayList<XWPFDocument> documentList = new ArrayList<>();
  41. XWPFDocument doc = null;
  42. for (int i = 0; i < srcfile.size(); i++) {
  43. FileInputStream in = new FileInputStream(srcfile.get(i).getPath());
  44. OPCPackage open = OPCPackage.open(in);
  45. XWPFDocument document = new XWPFDocument(open);
  46. documentList.add(document);
  47. in.close();
  48. }
  49. for (int i = 0; i < documentList.size(); i++) {
  50. doc = documentList.get(0);
  51. if(i != 0){
  52. appendBody(doc,documentList.get(i));
  53. }
  54. }
  55. // doc.createParagraph().setPageBreak(true);
  56. doc.write(dest);
  57. System.out.println(name);
  58. doc.close();
  59. dest.close();
  60. } catch (Exception e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. }
  65.  
  66. }
  67.  
  68. public static void appendBody(XWPFDocument src, XWPFDocument append) throws Exception {
  69. CTBody src1Body = src.getDocument().getBody();
  70. CTBody src2Body = append.getDocument().getBody();
  71.  
  72. List<XWPFPictureData> allPictures = append.getAllPictures();
  73. // 记录图片合并前及合并后的ID
  74. Map<String,String> map = new HashMap();
  75. for (XWPFPictureData picture : allPictures) {
  76. String before = append.getRelationId(picture);
  77. //将原文档中的图片加入到目标文档中
  78. String after = src.addPictureData(picture.getData(), Document.PICTURE_TYPE_PNG);
  79. map.put(before, after);
  80. }
  81.  
  82. appendBody(src1Body, src2Body,null);
  83.  
  84. }
  85.  
  86. private static void appendBody(CTBody src, CTBody append,Map<String,String> map) throws Exception {
  87. XmlOptions optionsOuter = new XmlOptions();
  88. optionsOuter.setSaveOuter();
  89. String appendString = append.xmlText(optionsOuter);
  90.  
  91. String srcString = src.xmlText();
  92. String prefix = srcString.substring(0,srcString.indexOf(">")+1);
  93. String mainPart = srcString.substring(srcString.indexOf(">")+1,srcString.lastIndexOf("<"));
  94. String sufix = srcString.substring( srcString.lastIndexOf("<") );
  95. String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
  96.  
  97. if (map != null && !map.isEmpty()) {
  98. //对xml字符串中图片ID进行替换
  99. for (Map.Entry<String, String> set : map.entrySet()) {
  100. addPart = addPart.replace(set.getKey(), set.getValue());
  101. }
  102. }
  103. //将两个文档的xml内容进行拼接
  104. CTBody makeBody = CTBody.Factory.parse(prefix+addPart+mainPart+sufix);
  105.  
  106. src.set(makeBody);
  107. }
  108.  
  109. private static void getAllFile(final List<File> subFileList, File fileRoot) {
  110. fileRoot.listFiles(new FileFilter() {
  111. @Override
  112. public boolean accept(File file) {
  113. if (file.isDirectory()) {
  114. getAllFile(subFileList, file);
  115. return false;
  116. }else{
  117. if(file.getName().endsWith(".docx")){
  118. subFileList.add(file);
  119. }
  120. return false;
  121. }
  122. }
  123. });
  124. }
  125. }

合并两个word文档,保持样式不变的更多相关文章

  1. C# 合并及拆分Word文档

    本文简要分析一下如何如何使用C#简单实现合并和拆分word文档.平时我们在处理多个word文档时,可能会想要将两个文档合并为一个,或者是将某个文档的一部分添加到另一个文档中,有的时候也会想要将文档拆分 ...

  2. C#/VB.NET 比较两个Word文档差异

    本文以C#和VB.NET代码为例,来介绍如何对比两个Word文档差异.程序中使用最新版的Spire.Doc for .NET 版本8.8.2.编辑代码前,先在VS程序中添加引用Spire.Doc.dl ...

  3. C# 实现将多个word文档合并成一个word文档的功能

    前段时间项目上遇到这么一个需求,需要将多个OCR识别的word文档合并成一个,于是就在网上找了找,自己修改了一下.在这里跟大家分享一下,希望有用的到的. 要做多word文档合并,首先要导入Micros ...

  4. JAVA合并多个word文档根据文章标题生成目录

    此产品版本是免费版的,我也是在用免费,除了只能单次识别25张一下的word和生成pdf有限制,其他的功能都和正式版差不多. 如果你几十个文档,每个文档几页,输出出来超过25页,那没关系,依然可以使用. ...

  5. Java 比较两个Word文档差异

    本文介绍使用Spire.Doc for Java的比较功能来比较两个相似Word文档的差异.需要使用的版本为3.8.8或者后续发布的新版本.可下载jar包,解压将lib文件夹下的Spire.doc.j ...

  6. C# 之 比较两个word文档的内容

    利用 Microsoft.Office.Interop.Word 组件进行比较.引入命名空间:using Word2013 = Microsoft.Office.Interop.Word; 代码如下: ...

  7. 用WPS查看两篇word文档异同之处

    写的合同,后期又有修改,电脑里同样名字的合同有好几个版本,不知道有什么不同,怎么办? 打开wps-->[审阅]-->[比较],剩下的按照提示很容易,略...

  8. C#使用NPOI对Word文档进行导出操作的dll最新版2.5.1

    Npoi导出非模板 最近使用NPOI做了个导出Word文档的功能,因为之前都是导出Excel很方便(不用模板),所以导出Word也选用了Npoi(也没有用模板,

  9. POI生成word文档完整案例及讲解

    一,网上的API讲解 其实POI的生成Word文档的规则就是先把获取到的数据转成xml格式的数据,然后通过xpath解析表单式的应用取值,判断等等,然后在把取到的值放到word文档中,最后在输出来. ...

随机推荐

  1. OBU设备非接触式读卡方案:SI522

    传统收费站将成历史!全部转为ETC系统 当高速人工收费已经成为我们驾驶出行的习惯后,我们发现,高速人工收费带来低效率.长等待以及落后性等缺点逐渐给人们出行带来不便.伴随着我国汽车保有量的逐年递增,高速 ...

  2. jmeter抓取cnode网站token值

    前置条件:已经登录 1.线程组下面先添加HTTP信息头管理器 1.1 jmeter向服务器发送http请求时,需要验证 cookie的等设置信息给到服务器去识别,因此,在发送请求前,我们一般会把相关需 ...

  3. Android的事件处理机制之基于监听的事件处理

    无论是桌面应用还是手机应用程序,面对用户的使用,经常需要处理的便是用户的各种动作,也就是需要为用户动作提供响应,这种为用户动作提供响应的机制就是事件处理. 而Android为我们提供了两套强大的响应机 ...

  4. Day8 - A - Points on Line CodeForces - 251A

    Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. N ...

  5. Java中JSON字符串与java对象的互换实例详解(转)

    http://www.jb51.net/article/90914.htm 在开发过程中,经常需要和别的系统交换数据,数据交换的格式有XML.JSON等,JSON作为一个轻量级的数据格式比xml效率要 ...

  6. hadoop 配置问题以及HDFS下如何读写文件

    辛辛苦苦学两年 ,一举回到解放前!!! 大数据开始学真的头疼 关键是linux你玩的不6 唉难受 hadoop 配置参见博客 http://dblab.xmu.edu.cn/blog/install- ...

  7. 如何用hugo搭建个人博客

    如何用hugo搭建个人博客 1. 安装 Hugo 点击跳转 Hugo Releases win10 步骤: 下载解压 , 然后添加环境变量 测试: #命令行测试 hugo version 2. 创建站 ...

  8. Jenkins实现自动打包,MAVEN打包,Shell脚本启动

    1.点击New任务 2.创建任务,输入项目名 3.输入描述等 4.选择Git或SVN 5.自动,定时打包 6.在Build下配置

  9. poj3405 Corporate Identity

    和上一个1226一样吧,这个还不用翻转 然而本蒟蒻还是写不对,WA一片天,不知道自己搞什么,自从去了长沙感觉就是坑啊 while(1) iq--; /*#include <cstdio> ...

  10. 167-PHP 文本分割函数str_split(二)

    <?php $str='PHP is a very good programming language'; //定义一个字符串 $arr=explode(' ',$str,-3); //使用空格 ...