Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Automating Word Document Consolidation with Python and COM

Tech 3

To merge multiple Word documents through a graphical interface, the following implementation utliizes the pywin32 library for COM automation and tkinter for the folder selection dialog. The solution assumes source files follow a numeric naming convention (e.g., 1.docx, 2.docx) to maintain sequential order during consolidation.

import tkinter as tk
from tkinter import filedialog, messagebox
from pathlib import Path
import re
import win32com.client

class WordConsolidator:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("Document Merger")
        self.window.geometry("500x150")
        self.selected_path = tk.StringVar()
        self.build_interface()
        
    def build_interface(self):
        tk.Label(self.window, text="Source Directory:").grid(row=0, column=0, padx=5, pady=5)
        tk.Entry(self.window, textvariable=self.selected_path, width=40).grid(row=0, column=1, padx=5)
        tk.Button(self.window, text="Browse", command=self.pick_directory).grid(row=0, column=2, padx=5)
        tk.Button(self.window, text="Execute Merge", command=self.process_documents).grid(row=1, column=1, pady=20)
        
    def pick_directory(self):
        directory = filedialog.askdirectory()
        if directory:
            self.selected_path.set(directory)
            
    def process_documents(self):
        target_dir = Path(self.selected_path.get())
        if not target_dir.exists():
            return
            
        try:
            self.combine_documents(target_dir)
            messagebox.showinfo("Complete", f"Output saved to {target_dir / 'combined.docx'}")
        except Exception as error:
            messagebox.showerror("Failure", str(error))
        finally:
            self.window.destroy()
            
    def combine_documents(self, source_folder):
        # Filter for Word files
        candidates = [f for f in source_folder.iterdir() 
                     if f.suffix.lower() in {'.doc', '.docx'}]
        
        # Sort by leading numeric value in filename
        def numeric_key(file_obj):
            digits = re.match(r'^(\d+)', file_obj.stem)
            return int(digits.group(1)) if digits else float('inf')
            
        candidates.sort(key=numeric_key)
        
        word_app = win32com.client.Dispatch("Word.Application")
        word_app.Visible = False
        
        try:
            composite = word_app.Documents.Add()
            
            for index, file_ref in enumerate(candidates):
                insertion_point = composite.Content
                if index > 0:
                    insertion_point.Collapse(Direction=0)  # 0 = wdCollapseEnd
                insertion_point.InsertFile(str(file_ref.absolute()))
                
            output_file = source_folder / "combined.docx"
            composite.SaveAs(str(output_file))
            composite.Close(SaveChanges=False)
        finally:
            word_app.Quit()

if __name__ == "__main__":
    merger = WordConsolidator()
    merger.window.mainloop()

Filename Indexing Requirement

The sorting mechanism extracts leading integers from filenames to determine insertion order. Files should be named with numeric prefixes (e.g., 001_intro.docx, 002_content.docx). The regular expression ^(\d+) captures these digits, defaulting to infinity for non-conforming names to place them at the end.

COM Automation Details

The script instantiates Word through COM dispatch, creating a blank document that serves as the destination. Each source file inserts at the end of the growing document using InsertFile. The wdCollapseEnd constant (value 0) ensures subsequent files append rather than overwrite previous content. The Word application terminates via Quit() regardless of success or failure to prevent orphaned processes.

This approach processes both .doc and .docx formats seamlessly, outputting a single combined.docx in the selected directory.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.