码农的狗蛋 2023-05-26 12:02 采纳率: 47.9%
浏览 17

请问怎么给多个文档合并下面加上页码啊(标签-List|关键词-Map)

请问怎么给多个文档合并下面加上页码啊

package com.kwm.referencemark.test;

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;

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;
/**
 * 合成word文档工具类
 * @ClassName: CompoundWordUtil
 */
public class CompoundWordUtil {
    public static void main (String[] args) throws Exception {
        File newFile = new File("C:/Users/v-guoxiao/Documents/trademark/TMReferencemark/testfile/Paticulars.docx");
        List<File> srcfile = new ArrayList<>();

        File file1 = new File("C:/Users/v-guoxiao/Documents/trademark/TMReferencemark/testfile/test1.docx");
        File file2 = new File("C:/Users/v-guoxiao/Documents/trademark/TMReferencemark/testfile/test2.docx");
        srcfile.add(file1);
        srcfile.add(file2);

        try {
            OutputStream dest = new FileOutputStream(newFile);
            ArrayList<XWPFDocument> documentList = new ArrayList<>();
            XWPFDocument doc = null;
            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);
            }
            for (int i = 0; i < documentList.size(); i++) {
                doc = documentList.get(0);
                if(i == 0){//首页直接分页,不再插入首页文档内容
                    documentList.get(i).createParagraph().createRun().addBreak(BreakType.PAGE);
//                    appendBody(doc,documentList.get(i));
                }else if(i == documentList.size()-1){//尾页不再分页,直接插入最后文档内容
                    appendBody(doc,documentList.get(i));
                }else{
                    documentList.get(i).createParagraph().createRun().addBreak(BreakType.PAGE);
                    appendBody(doc,documentList.get(i));
                }
            }
            doc.write(dest);
            System.out.println("*****合成成功********");
            Runtime.getRuntime().exec("cmd /c start winword C:/Users/v-guoxiao/Documents/trademark/TMReferencemark/testfile/Paticulars.docx");//直接调用cmd打开合成文档
        } 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<String,String>();
        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 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("<"));
        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);
    }
}

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2023-05-26 20:11
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:
    • 你可以参考下这篇文章:Map集合和List集合总结
    • 除此之外, 这篇博客: 封装数据到List集合和Map集合中的 封装数据到Map集合 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:
      • 声明map集合
      public class MapAction extends ActionSupport{
      
              private Map<String,User> map;
      
              @Override
                  public String execute() throws Exception {
                     System.out.println(map);
                      return NONE;
                  }
      }
      • 生成get和set方法
      public class MapAction extends ActionSupport{
      
              private Map<String,User> map;//这里的User类还是和上面的一样
      
      
      
              public Map<String, User> getMap() {
                  return map;
              }
      
      
      
              public void setMap(Map<String, User> map) {
                  this.map = map;
              }
      
      
      
                  @Override
                  public String execute() throws Exception {
                     System.out.println(map);
                     System.out.println(map.get("one").getAddress());
                     System.out.println(map.get("two").getUsername());
                      return NONE;
                  }
      }
      • 在表单输入项的name属性值里面写表达式
      <%@ page language="java" contentType="text/html; charset=UTF-8"
          pageEncoding="UTF-8"%>
      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
      <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>Insert title here</title>
      </head>
      <body>
                <form action="${pageContext.request.contextPath}/map.action" method="post">
                    username:<input type="text" name="map['one'].username"/>
                    <br/>
                    password:<input type="text" name="map['one'].password"/>
                    <br/>
                    address:<input type="text" name="map['one'].address"/>
                    <br/><br/>
                  username:<input type="text" name="map['two'].username"/>
                    <br/>
                    password:<input type="text" name="map['two'].password"/>
                    <br/>
                    address:<input type="text" name="map['two'].address"/>
                    <br/>
                    <input type="submit" value="提交"/>
             </form>
      </body>
      </html>

      struts.xml

       <action name="map" class="cn.zhoushicanyin.date.MapAction">          
      </action>

      这里写图片描述

      这里写图片描述


    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

问题事件

  • 创建了问题 5月26日

悬赏问题

  • ¥15 错误使用 gretna_GUI_PreprocessInterface>RunBtn_Callback
  • ¥15 WPF如何用Chart绘画出Y轴的左边数据
  • ¥15 pycharm无法查看内置代码
  • ¥15 跑hls xfopencv的例程standalone_hls_axi_example出的错误,csim没问题,c synthesis出的错误
  • ¥15 sqlserver update语句逐行生效
  • ¥20 Windows10系统命令行调用
  • ¥15 php环境如何实现国密SM2相关功能
  • ¥15 关于#单片机#的问题:K210 例程里面提示我iomem.h: No such file or directory
  • ¥15 LSPI算法的大问题
  • ¥15 java导出word 动态填充数据