Merge Docx Documents
Mohamad's interest is in Programming (Mobile, Web, Database and Machine Learning). He is studying at the Center For Artificial Intelligence Technology (CAIT), Universiti Kebangsaan Malaysia (UKM).
Upload multiple DOCX files.
Sort filenames A → Z.
Merge them into one document.
Automatically insert a page break before every Heading 1 paragraph (except the very first Heading 1 in the merged document).
Download the final document.
# Install package
!pip install python-docx -q
from google.colab import files
from docx import Document
from copy import deepcopy
# =====================================================
# Upload files
# =====================================================
print("Select DOCX files...")
uploaded = files.upload()
# =====================================================
# Sort files alphabetically
# =====================================================
docx_files = sorted(
[f for f in uploaded.keys() if f.lower().endswith(".docx")]
)
print("\nFiles to merge:")
for f in docx_files:
print(f)
# =====================================================
# Create merged document
# =====================================================
merged_doc = Document()
# Remove default empty paragraph
if merged_doc.paragraphs:
p = merged_doc.paragraphs[0]._element
p.getparent().remove(p)
first_heading1_found = False
# =====================================================
# Merge documents
# =====================================================
for filename in docx_files:
print(f"Merging {filename}")
src = Document(filename)
for para in src.paragraphs:
style_name = para.style.name if para.style else ""
# Start every Heading 1 on a new page
if style_name == "Heading 1":
if first_heading1_found:
merged_doc.add_page_break()
else:
first_heading1_found = True
new_para = merged_doc.add_paragraph(style=para.style)
# Copy text and formatting
for run in para.runs:
new_run = new_para.add_run(run.text)
new_run.bold = run.bold
new_run.italic = run.italic
new_run.underline = run.underline
if run.font:
new_run.font.name = run.font.name
new_run.font.size = run.font.size
# =====================================================
# Save output
# =====================================================
output_file = "Merged_Document.docx"
merged_doc.save(output_file)
print(f"\nSaved: {output_file}")
files.download(output_file)
