GVKun编程网logo

使用python docx合并word文档(python docx 合并)

23

本文将带您了解关于使用pythondocx合并word文档的新内容,同时我们还将为您解释pythondocx合并的相关知识,另外,我们还将为您提供关于C#实现简单合并word文档的方法、Java合并W

本文将带您了解关于使用python docx合并word文档的新内容,同时我们还将为您解释python docx 合并的相关知识,另外,我们还将为您提供关于C#实现简单合并word文档的方法、Java 合并Word文档、java中使用poi实现合并word文档,兼容图片的合并并分页、JAVA合并word文档生成目录的实用信息。

本文目录一览:

使用python docx合并word文档(python docx 合并)

使用python docx合并word文档(python docx 合并)

我只有几个Word文件,每个文件都有特定的内容。我想要一个显示给我的片段,或者帮助我弄清楚如何在使用Pythondocx库的同时将word文件合并为一个文件。

例如,在pywin32库中,我执行以下操作:

rng = self.doc.Range(0, 0)for d in data:    time.sleep(0.05)    docstart = d.wordDoc.Content.Start    self.word.Visible = True    docend = d.wordDoc.Content.End - 1    location = d.wordDoc.Range(docstart, docend).Copy()    rng.Paste()    rng.Collapse(0)    rng.InsertBreak(win32.constants.wdPageBreak)

但是我需要在使用Pythondocx库而不是win32.client

答案1

小编典典

如果您的需求很简单,则可以使用以下方法:

source_document = Document(''source.docx'')target_document = Document()for paragraph in source_document.paragraphs:    text = paragraph.text    target_document.add_paragraph(text)

您还可以做其他事情,但这应该可以帮助您入门。

事实证明,在一般情况下,将内容从一个Word文件复制到另一个Word文件是相当复杂的,涉及诸如协调源文档中存在的样式之类的事情,例如与目标文档中可能存在冲突的事物。因此,这不是我们明年可能要添加的功能。

C#实现简单合并word文档的方法

C#实现简单合并word文档的方法

本文实例讲述了C#实现简单合并word文档的方法。分享给大家供大家参考。具体如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
namespace Demo
{
 public partial class Form2 : Form
 {
  public Form2()
  {
   InitializeComponent();
  }
  string path = @"C:\Documents and Settings\Administrator\桌面\output.doc";
  string add = @"C:\Documents and Settings\Administrator\桌面\file";
  private Microsoft.Office.Interop.Word.ApplicationClass applicationClass;
  private Microsoft.Office.Interop.Word.Document doc;
  private void button1_Click(object sender,EventArgs e)
  {
   Ex();
  }
  void Ex()
  {
   Open(path);
   string[] files = System.IO.Directory.GetFiles(add);
   foreach (string s in files)
   {
    InsertFile(s);
   }
   SaveAs(path);
  }
  /// <summary>
  /// 打开输出word文档
  /// </summary>
  /// <param name="strFileName"></param>
  public void Open(string strFileName)
  {
   applicationClass = new Microsoft.Office.Interop.Word.ApplicationClass();
   object fileName = strFileName;
   object readOnly = false;
   object isVisible = true;
   object missing = System.Reflection.Missing.Value;
   doc = applicationClass.Documents.Open(ref fileName,ref missing,ref missing);
   doc.Activate();
  }
  /// <summary>
  /// 向打开的word文档中插入word文档
  /// </summary>
  /// <param name="strFileName"></param>
  public void InsertFile(string strFileName)
  {
   object missing = System.Reflection.Missing.Value;
   object confirmConversion = false;
   object link = false;
   object attachment = false;
   applicationClass.Selection.InsertFile(strFileName,ref confirmConversion,ref link,ref attachment);
   object pBreak = (int)Microsoft.Office.Interop.Word.WdBreakType.wdSectionBreakNextPage;
   applicationClass.Selection.InsertBreak(ref pBreak);
  }
  /// <summary>
  /// 最后保存word文档
  /// </summary>
  /// <param name="strFileName"></param>
  public void SaveAs(string strFileName)
  {
   object missing = System.Reflection.Missing.Value;
   object fileName = strFileName;
   doc.SaveAs(ref fileName,ref missing);
  }
 }
}

@H_301_4@

希望本文所述对大家的C#程序设计有所帮助。

Java 合并Word文档

Java 合并Word文档

概述

在前文中,我写过关于如何使用Java程序来合并Excel及PDF文档的文章。那有关Word文档的合并方法将会在今天这篇文章里详细介绍。通常合并文档有两种方式,一种是直接将被合并文档的正文承接在上一个文档的最后一个段落末尾;另一种则是被合并文档的内容从新的一页开始显示。

此次代码演示所需工具是Free Spire.Doc for Java。请从官网上下载获取,解压后将lib文件夹下的Spire.Doc.jar导入IDEA中。

当然,你也可以通过maven仓库来安装产品及导入相应依赖。

代码演示

方式 1:使用Document类中的insertTextFromFile方法将不同的文档合并到同一个文档。需要注意的是,被合并文档的内容默认从新的一页开始显示。

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class MergeFiles1 {
    public static void main(String[] args) {
        //获取第一个文档的路径
        String filePath1 = "C:\\Users\\Test1\\Desktop\\Sample1.docx";
        //获取第二个文档的路径
        String filePath2 = "C:\\Users\\Test1\\Desktop\\Sample2.docx";

        //加载第一个文档
        Document document = new Document(filePath1);

        //使用insertTextFromFile方法将第二个文档的内容插入到第一个文档
        document.insertTextFromFile(filePath2, FileFormat.Docx_2013);

        //保存文档
        document.saveToFile("Output/MergeFiles1.docx", FileFormat.Docx_2013);
    }
}

生成文档:

效果1.png

方式 2:若需将新加入的文档承接到上一个文档的最后一个段落末尾,则可以使用下面的方法获取第一个文档的最后一个section,然后将被合并文档的正文作为新的段落添加到section。

import com.spire.doc.Document;
import com.spire.doc.DocumentObject;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;

public class MergeFiles2 {
    public static void main(String[] args) {
        //获取第一个文档的路径
        String filePath1 = "C:\\Users\\Test1\\Desktop\\Sample1.docx";
        //获取第二个文档的路径
        String filePath2 = "C:\\Users\\Test1\\Desktop\\Sample2.docx";

        //加载第一个文档
        Document document1 = new Document(filePath1);
        //加载第二个文档
        Document document2 = new Document(filePath2);

        //获取第一个文档的最后一个section
        Section lastSection = document1.getLastSection();

        //将第二个文档的段落作为新的段落添加到第一个文档的最后一个section
        for (Section section:(Iterable <Section>)document2.getSections()) {
            for (DocumentObject obj:(Iterable <DocumentObject>)section.getBody().getChildObjects()
            ) {
                lastSection.getBody().getChildObjects().add(obj.deepClone());
            }
        }

        //保存文档
        document1.saveToFile("Output/MergeFiles2.docx", FileFormat.Docx_2013);

    }
}

生成文档:

效果2.png

(本文完)

java中使用poi实现合并word文档,兼容图片的合并并分页

java中使用poi实现合并word文档,兼容图片的合并并分页

最近需要做一个java合并wrod的实现方法,网上查了看看发现有的方法word里的图片没办法正确的合并到目标文件。后来又查了下,综合了一下自己写了个测试方法,顺手记了一下。

package com.fosung.pb.develop.report.service;

import org.apache.poi.openxml4j.opc.OPCPackage;
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 test {
    public static void main (String[] args) throws Exception {

        File newFile = new File("f:\\张三_发展党员纪实材料.docx");
        List<File> srcfile = new ArrayList<>();
        File file1 = new File("F:\\report\\step3\\substep7.docx");
        File file2 = new File("F:\\report\\step3\\substep9.docx");
        File file3 = new File("F:\\report\\step3\\substep9-4.docx");
        File file4 = new File("F:\\report\\step2\\substep3.docx");
        srcfile.add(file2);
        srcfile.add(file1);
        srcfile.add(file3);
        srcfile.add(file4);
        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().setPageBreak(true);
                    appendBody(doc,documentList.get(i));
                }
            }
            doc.createParagraph().setPageBreak(true);
            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 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);
    }
}

 

刚开始合并后遇到了一个问题,就是合并完word后,所有表格都紧紧挨在了一起,没有分页。后来加上了分页符

documentList.get(i).createParagraph().setPageBreak(true);实现了分页效果。

JAVA合并word文档生成目录

JAVA合并word文档生成目录

下载jar包,或者引入相关maven

maven引入相关地址:https://www.e-iceblue.cn/licensing/install-spirepdf-for-java-from-maven-repository.html

jar包下载地址:点击下载

 

如果不知道怎么引入jar包到项目中,请面向百度。

 

如果word文档中已经设置了大纲就直接使用一段代码即可

 

public static void main(String[]args){
        //加载测试文档
        Document doc = new Document("测试文件.docx");

        //在文档最前面插入一个段落,写入文本并格式化
        Paragraph parainserted = new Paragraph(doc);
        TextRange tr= parainserted.appendText("目 录");
        tr.getCharacterFormat().setBold(true);
        tr.getCharacterFormat().setTextColor(Color.gray);
        doc.getSections().get(0).getParagraphs().insert(0,parainserted);
        parainserted.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        
        //手动设置文档中指定段落的大纲级别
        doc.getSections().get(0).getParagraphs().get(1).applyStyle(BuiltinStyle.Heading_1);
        doc.getSections().get(0).getParagraphs().get(2).applyStyle(BuiltinStyle.Heading_2);
        doc.getSections().get(0).getParagraphs().get(4).applyStyle(BuiltinStyle.Heading_2);
        doc.getSections().get(0).getParagraphs().get(6).applyStyle(BuiltinStyle.Heading_2);
        doc.getSections().get(0).getParagraphs().get(12).applyStyle(BuiltinStyle.Heading_2);
        doc.getSections().get(0).getParagraphs().get(13).applyStyle(BuiltinStyle.Heading_3);
        doc.getSections().get(0).getParagraphs().get(14).applyStyle(BuiltinStyle.Heading_3);
        doc.getSections().get(0).getParagraphs().get(15).applyStyle(BuiltinStyle.Heading_3);
        doc.getSections().get(0).getParagraphs().get(17).applyStyle(BuiltinStyle.Heading_1);
        doc.getSections().get(0).getParagraphs().get(18).applyStyle(BuiltinStyle.Heading_2);

        //添加目录
        doc.getSections().get(0).getParagraphs().get(0).appendTOC(1,3);

        //更新目录表
        doc.updateTableOfContents();

        //保存文档
        doc.saveToFile("目录.docx",FileFormat.Docx_2010);
    }

demo来源地址:https://www.e-iceblue.cn/spiredocforjavaformfield/add-word-toc-in-java.html

 

下面这个是没有设置大纲的文档生成目录,我的方案是把每页第一段设置为大纲,然后生成目录。

下面的是合并文档然后生成目录和页码的代码逻辑。

 

/**
    *    先临时生成一个合并完成后的docx格式文档,doc会出现乱码。
    * @param pathList 所有需要合并的文档的绝对路径
    * @param savePath 一个路径,但是没有文件的后缀,之后进行拼接。
    * @return 状态,是否保存成功
    */
   public static boolean mergeWordToPdf(List<String> pathList, String savePath){
       //判断是否为pdf文件后缀的路径
//       String[] split = savePath.split("\\.");
//       if (!"pdf".equals(split[split.length-1])) {
//           System.out.println("请给一个以pdf保存路径结尾的路径");
//           return false;
//       }
       //保存合并完成后临时存放的文件
       String file =  savePath + ".docx";
       File newfile = new File(file);
       try {
           //判断是否存在,存在则删除
           if (newfile.exists()) {
               newfile.delete();
           }
           newfile.createNewFile();
           //创建一个新的doc文件
           Document doc = new Document(file);
           int count = 0;
           // 进行合并
           for (String filePath : pathList) {
               // 获取文档的路径,然后合并
               count++;
               Document doc2 = new Document();
               doc2.loadFromFile(filePath);
               for (int j = 0; j < doc2.getSections().getCount(); j++) {
                   doc.getSections().add(doc2.getSections().get(j).deepClone());
               }
           }

           // 在开头创建一个目录页
           ParagraphStyle title1style = new ParagraphStyle(doc);
           title1style.setName("TL1");
           title1style.getParagraphFormat().setOutlineLevel(OutlineLevel.Level_1);
           doc.getStyles().add(title1style);
           Section sec = doc.getSections().get(0);
           //设置边距
           sec.getPageSetup().getMargins().setTop(71.882f);
           sec.getPageSetup().getMargins().setBottom(71.882f);
           sec.getPageSetup().getMargins().setLeft(90f);
           sec.getPageSetup().getMargins().setRight(90f);
           sec.getParagraphs().get(0).applyStyle(title1style.getName());

           //循环遍历每一页的标题,并添加到目录页中
           for (int i = 1; i <= count; i++) {
               sec = doc.getSections().get(i);
               sec.getParagraphs().get(0).applyStyle(title1style.getName());
           }
           sec = doc.getSections().get(0);
           Paragraph para = new Paragraph(doc);
           sec.getParagraphs().insert(0, para);
           TableOfContent toc = para.appendTOC(1, 3);
           toc.setUseHeadingStyles(false);
           toc.setUseHyperlinks(true);
           toc.setUseTableEntryFields(false);
           toc.setRightAlignPageNumbers(true);
           toc.setTOCLevelStyle(1, title1style.getName());
           doc.isUpdateFields();
           doc.updateTableOfContents();

           //设置目录的字体
           TextRange range = para.appendText("目录");
           range.getCharacterFormat().setFontName("宋体");
           range.getCharacterFormat().setFontSize(16);
           para.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
           sec.getParagraphs().insert(0, para);
           for (int i = 0; i < sec.getParagraphs().getCount(); i++) {
               Paragraph p = sec.getParagraphs().get(i);
               if (p.getStyleName().equals("TOC1")) {
                   for (int j = 0; j < p.getChildObjects().getCount(); j++) {
                       if (p.getChildObjects().get(j).getDocumentObjectType().equals(DocumentObjectType.Text_Range)) {
                           TextRange range0 = (TextRange) p.getChildObjects().get(j);
                           range0.getCharacterFormat().setFontName("宋体");
                           range0.getCharacterFormat().setBold(false);
                       }
                   }
               }
           }
           //删除页眉
           for (int i = 1; i <= count; i++) {
               ParagraphCollection paragraphsHeader = doc.getSections().get(i).getHeadersFooters().getHeader().getParagraphs();
               if (paragraphsHeader.getCount() > 0) {
                   paragraphsHeader.removeAt(0);
               }
               doc.getSections().get(i).getHeadersFooters().getFirstPageFooter().getChildObjects().clear();
               doc.getSections().get(i).getHeadersFooters().getOddFooter().getChildObjects().clear();
           }

           //添加文字、页码域和总页数域到段落
           Paragraph paragraph = doc.getSections().get(0).getHeadersFooters().getFirstPageFooter().addParagraph();
           paragraph.appendField("page number", FieldType.Field_Page);
           paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);

           Paragraph paragraph1 = doc.getSections().get(0).getHeadersFooters().getOddFooter().addParagraph();
           paragraph1.appendField("page number", FieldType.Field_Page);
           paragraph1.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);
           
           //在转换为pdf时出现字体便乱的情况,格式化字体后解决。如果不需要转换为pdf,此操作可以删除。
           for (int a = 1; a <= count; a++) {
               Section s = doc.getSections().get(a);
               //更新全文的字体(不包括tbale里的)
               for (int i = 1; i < s.getParagraphs().getCount(); i++) {
                   Paragraph p = s.getParagraphs().get(i);
                   for (int j = 0; j < p.getChildObjects().getCount(); j++) {
                       if (p.getChildObjects().get(j).getDocumentObjectType().equals(DocumentObjectType.Text_Range)) {
                           TextRange range0 = (TextRange) p.getChildObjects().get(j);
                           range0.getCharacterFormat().setFontName("宋体");
                           range0.getCharacterFormat().setBold(false);
                       }
                   }
               }
               TableCollection tables = s.getTables();
               //更新table里字体
               if (tables.getCount() > 0) {
                   updateTable(tables);
               }
           }

           //保存word文件
           doc.saveToFile(file, FileFormat.Docx);
           //转换为pdf,转换的代码在下一篇文章里,使用的不是同一个jar包,因为这个jar对生成pdf没有限制,准确的说是破*了。
           //WordToPdfUtil.wordToPdf(file, savePath + ".pdf");return true;
       }catch (Exception e){
           e.printStackTrace();
       }
       return false;
   }

 

可能每个人的需求都不一样,不过你可以去查看相关Api或者官方demo进行修改。

 

此产品版本是免费版的,我也是在用免费,除了只能单次识别25张一下的word和生成pdf有限制,其他的功能都和正式版差不多。

如果你几十个文档,每个文档几页,输出出来超过25页,那没关系,依然可以使用。别单个文档超过25页即可。

如果公司使用,请支持购买收费版。

 

 

转换pdf的文章路径:

https://www.cnblogs.com/hunmeng/p/11983882.html

原文出处:https://www.cnblogs.com/hunmeng/p/11983701.html

今天关于使用python docx合并word文档python docx 合并的分享就到这里,希望大家有所收获,若想了解更多关于C#实现简单合并word文档的方法、Java 合并Word文档、java中使用poi实现合并word文档,兼容图片的合并并分页、JAVA合并word文档生成目录等相关知识,可以在本站进行查询。

本文标签: