小白教程

 找回密码
 立即注册
查看: 5692|回复: 2

[已回复] 使用python-docx合并(合并)Word文档

[复制链接]

1

主题

4

帖子

8

积分

新手上路

Rank: 1

积分
8
发表于 2021-5-17 05:48:02 | 显示全部楼层 |阅读模式
我正在尝试使用python-docx将多个.docx文件合并为一个。
MKA-20-5778-0-1.docx ',' MKA-20-5967-0-1.docx这是源文件,将从内容中获取。
empty.docx-空白的工作表。
合并的结果保存在Combined_word_documents.docx中。结果,我得到了空白。为什么?
  1. from docx import Document
  2. files = ['МКА-20-5778-0-1.docx', 'МКА-20-5967-0-1.docx']


  3. def combine_word_documents(files):
  4.     combined_document = Document('empty.docx')
  5.     count, number_of_files = 0, len(files)
  6.     for file in files:
  7.         sub_doc = Document(file)

  8.         # Don't add a page break if you've
  9.         # reached the last file.
  10.         if count < number_of_files - 1:
  11.             sub_doc.add_page_break()

  12.         for paragraph in sub_doc.paragraphs:
  13.             text = paragraph.text
  14.             combined_document.add_paragraph(text)
  15.         count += 1

  16.     combined_document.save('combined_word_documents.docx')

  17. combine_word_documents(files)
复制代码


本帖寻求最佳方案

回复被采纳后将获得奖励 C币 5 ,目前已有 2 个回复 我要奖励
回复

使用道具 举报

0

主题

5

帖子

10

积分

新手上路

Rank: 1

积分
10
发表于 2021-5-17 05:49:29 | 显示全部楼层
我认为您可以使用docxcompose:
  1. from docx import Document
  2. from docxcompose.composer import Composer
  3.    
  4. master = Document("out.docx")
  5. composer = Composer(master)
  6. doc1 = Document("in.docx")
  7. composer.append(doc1)
  8. master.save('out.docx')
复制代码


回复

使用道具 举报

1

主题

2

帖子

5

积分

新手上路

Rank: 1

积分
5
发表于 2021-5-17 06:11:54 | 显示全部楼层
  1. rng = self.doc.Range(0, 0)
  2. for d in data:
  3.     time.sleep(0.05)

  4.     docstart = d.wordDoc.Content.Start
  5.     self.word.Visible = True
  6.     docend = d.wordDoc.Content.End - 1
  7.     location = d.wordDoc.Range(docstart, docend).Copy()
  8.     rng.Paste()
  9.     rng.Collapse(0)
  10.     rng.InsertBreak(win32.constants.wdPageBreak)
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 14:51 , Processed in 0.387712 second(s), 23 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

快速回复 返回顶部 返回列表