docx-templates-6-mail-merge-and-batch-generation

Sub-skill of docx-templates: 6. Mail Merge and Batch Generation.

5 stars

Best use case

docx-templates-6-mail-merge-and-batch-generation is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Sub-skill of docx-templates: 6. Mail Merge and Batch Generation.

Teams using docx-templates-6-mail-merge-and-batch-generation should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/6-mail-merge-and-batch-generation/SKILL.md --create-dirs "https://raw.githubusercontent.com/vamseeachanta/workspace-hub/main/.agents/skills/_archive/data/office/docx-templates/6-mail-merge-and-batch-generation/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/6-mail-merge-and-batch-generation/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How docx-templates-6-mail-merge-and-batch-generation Compares

Feature / Agentdocx-templates-6-mail-merge-and-batch-generationStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Sub-skill of docx-templates: 6. Mail Merge and Batch Generation.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# 6. Mail Merge and Batch Generation

## 6. Mail Merge and Batch Generation


**Generating Multiple Documents:**
```python
"""
Generate multiple documents from a template with different data.
"""
from docxtpl import DocxTemplate
from typing import List, Dict, Any, Iterator
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
import csv
import json
import pandas as pd

def mail_merge_from_list(
    template_path: str,
    output_dir: str,
    records: List[Dict[str, Any]],
    filename_field: str = "id"
) -> List[str]:
    """
    Generate documents for multiple records.

    Args:
        template_path: Path to template
        output_dir: Directory for output files
        records: List of data records
        filename_field: Field to use for output filename

    Returns:
        List of generated file paths
    """
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)

    generated_files = []

    for record in records:
        # Load fresh template for each document
        template = DocxTemplate(template_path)

        # Generate filename
        filename = f"{record.get(filename_field, 'document')}.docx"
        file_path = output_path / filename

        # Render and save
        template.render(record)
        template.save(str(file_path))

        generated_files.append(str(file_path))

    print(f"Generated {len(generated_files)} documents in {output_dir}")
    return generated_files


def mail_merge_from_csv(
    template_path: str,
    csv_path: str,
    output_dir: str,
    filename_field: str = "id"
) -> List[str]:
    """
    Generate documents from CSV data source.

    Args:
        template_path: Path to template
        csv_path: Path to CSV file
        output_dir: Directory for output files
        filename_field: Field to use for output filename

    Returns:
        List of generated file paths
    """
    with open(csv_path, 'r', newline='', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        records = list(reader)

    return mail_merge_from_list(template_path, output_dir, records, filename_field)


def mail_merge_from_excel(
    template_path: str,
    excel_path: str,
    output_dir: str,
    sheet_name: str = None,
    filename_field: str = "id"
) -> List[str]:
    """
    Generate documents from Excel data source.

    Args:
        template_path: Path to template
        excel_path: Path to Excel file
        output_dir: Directory for output files
        sheet_name: Sheet to read (default: first sheet)
        filename_field: Field to use for output filename

    Returns:
        List of generated file paths
    """
    df = pd.read_excel(excel_path, sheet_name=sheet_name)
    records = df.to_dict('records')

    return mail_merge_from_list(template_path, output_dir, records, filename_field)


def mail_merge_parallel(
    template_path: str,
    output_dir: str,
    records: List[Dict[str, Any]],
    filename_field: str = "id",
    max_workers: int = 4
) -> List[str]:
    """
    Generate documents in parallel for better performance.

    Args:
        template_path: Path to template
        output_dir: Directory for output files
        records: List of data records
        filename_field: Field to use for output filename
        max_workers: Maximum parallel workers

    Returns:
        List of generated file paths
    """
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)

    def generate_single(record: Dict) -> str:
        """Generate a single document."""
        template = DocxTemplate(template_path)
        filename = f"{record.get(filename_field, 'document')}.docx"
        file_path = output_path / filename

        template.render(record)
        template.save(str(file_path))

        return str(file_path)

    generated_files = []

    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = {executor.submit(generate_single, r): r for r in records}

        for future in as_completed(futures):
            try:
                result = future.result()
                generated_files.append(result)
            except Exception as e:
                record = futures[future]
                print(f"Error generating document for {record.get(filename_field)}: {e}")

    print(f"Generated {len(generated_files)} documents")
    return generated_files


class MailMergeGenerator:
    """
    Full-featured mail merge generator.
    """

    def __init__(self, template_path: str):
        self.template_path = template_path
        self._validate_template()

    def _validate_template(self) -> None:
        """Validate template file exists."""
        if not Path(self.template_path).exists():
            raise FileNotFoundError(f"Template not found: {self.template_path}")

    def _get_template_variables(self) -> List[str]:
        """Extract variable names from template."""
        template = DocxTemplate(self.template_path)
        return list(template.get_undeclared_template_variables())

    def validate_data(self, records: List[Dict]) -> Dict[str, List]:
        """
        Validate data against template variables.

        Returns:
            Dict with 'missing' and 'extra' variable lists
        """
        template_vars = set(self._get_template_variables())


*Content truncated — see parent skill for full reference.*

Related Skills

work-around-merge-conflicts-in-test-execution

5
from vamseeachanta/workspace-hub

Run tests when repo has unresolved merge conflicts in config files by bypassing broken configs and executing tests directly

label-driven-prompt-generation-architecture

5
from vamseeachanta/workspace-hub

Pattern for building automation scripts that classify GitHub issues into prompt templates using label-based routing and extract contextual data for batch processing

batch-syntax-repair-from-injection-errors

5
from vamseeachanta/workspace-hub

Detect and fix systematic syntax errors caused by line-injection scripts that split multiline constructs

batch-syntax-fix-with-regex-line-based-fallback

5
from vamseeachanta/workspace-hub

Fix repeated syntax errors across many files using regex, then fall back to line-based parsing when regex fails

batch-syntax-fix-regex-iteration

5
from vamseeachanta/workspace-hub

Iteratively fix widespread syntax errors across many files using regex refinement when initial patterns fail

batch-syntax-fix-pattern

5
from vamseeachanta/workspace-hub

Identify and repair cascading import/syntax errors across multiple files using regex-based line-scanning and verification

batch-regex-fix-import-syntax

5
from vamseeachanta/workspace-hub

Detect and fix mid-import blank-line syntax breaks across multiple files using line-based regex

agent-team-prompt-generation

5
from vamseeachanta/workspace-hub

Create self-contained execution prompts that define multi-role workflows for Codex sessions without external dependencies

gtm-workflow-gif-generation

5
from vamseeachanta/workspace-hub

Generate workflow-style GTM GIFs from validated HTML demo reports using synthetic scene slides plus Playwright/Pillow scroll capture, with Python 3.12 fallback and GIF size optimization.

gtm-demo-workflow-gif-generation

5
from vamseeachanta/workspace-hub

Generate GTM demo GIF assets from validated HTML reports, including both report-scroll GIFs and one higher-fidelity workflow-style GIF, while avoiding Playwright/Python environment traps.

closure-first-overnight-batch

5
from vamseeachanta/workspace-hub

Run a high-leverage overnight batch by clearing stale-open approved issues first, converting shared blockers into tracked issues, and reserving only one lane for true implementation.

workspace-hub-batch-issue-execution

5
from vamseeachanta/workspace-hub

Deprecated alias for gh-work-execution.