如何编写批量转换文档模板脚本

wen 实用脚本 2

本文目录导读:

如何编写批量转换文档模板脚本

  1. Python脚本方案(最灵活)
  2. Shell脚本方案(适合Linux/Mac)
  3. PowerShell脚本方案(适合Windows)
  4. 使用Python处理多种文档格式
  5. 使用建议

我来为您介绍几种编写批量文档模板转换脚本的方法,涵盖不同场景和使用需求。

Python脚本方案(最灵活)

使用python-docx处理Word文档

import os
import glob
from docx import Document
from docx.shared import Pt, Inches
import re
class DocumentTemplateConverter:
    def __init__(self, template_path):
        self.template = Document(template_path)
        self.template_path = template_path
    def convert_single_document(self, input_path, output_path, replacements=None):
        """转换单个文档"""
        doc = Document(input_path)
        # 替换文档中的占位符
        if replacements:
            self._replace_text(doc, replacements)
        # 应用模板样式
        self._apply_template_style(doc)
        # 保存文档
        doc.save(output_path)
        print(f"已转换: {input_path} -> {output_path}")
    def _replace_text(self, doc, replacements):
        """替换文档中的文本"""
        for paragraph in doc.paragraphs:
            for search, replace in replacements.items():
                if search in paragraph.text:
                    paragraph.text = paragraph.text.replace(search, replace)
        # 替换表格中的文本
        for table in doc.tables:
            for row in table.rows:
                for cell in row.cells:
                    for paragraph in cell.paragraphs:
                        for search, replace in replacements.items():
                            if search in paragraph.text:
                                paragraph.text = paragraph.text.replace(search, replace)
    def _apply_template_style(self, doc):
        """应用模板样式"""
        # 复制模板的样式设置
        for style in self.template.styles:
            if style.type == 1:  # 段落样式
                try:
                    doc.styles[style.name].font.name = style.font.name
                    doc.styles[style.name].font.size = style.font.size
                except:
                    pass
    def batch_convert(self, input_folder, output_folder, file_pattern="*.docx", 
                      replacements=None):
        """批量转换文件夹中的文档"""
        # 创建输出文件夹
        os.makedirs(output_folder, exist_ok=True)
        # 获取所有匹配的文件
        input_files = glob.glob(os.path.join(input_folder, file_pattern))
        for input_path in input_files:
            filename = os.path.basename(input_path)
            output_path = os.path.join(output_folder, filename)
            self.convert_single_document(input_path, output_path, replacements)
# 使用示例
def main():
    # 定义替换规则
    replacements = {
        "{{公司名称}}": "ABC科技有限公司",
        "{{日期}}": "2024年1月15日",
        "{{项目名称}}": "文档转换项目"
    }
    # 创建转换器实例
    converter = DocumentTemplateConverter("template.docx")
    # 批量转换
    converter.batch_convert(
        input_folder="./input_docs",
        output_folder="./output_docs",
        file_pattern="*.docx",
        replacements=replacements
    )
if __name__ == "__main__":
    main()

Shell脚本方案(适合Linux/Mac)

使用sed和awk处理文本文件

#!/bin/bash
# 批量文档模板转换脚本
# 适用于文本文件、Markdown、LaTeX等
# 配置变量
INPUT_DIR="./input"
OUTPUT_DIR="./output"
TEMPLATE_FILE="./template.txt"
# 替换规则
declare -A REPLACEMENTS
REPLACEMENTS["{{DATE}}"]="$(date +%Y-%m-%d)"
REPLACEMENTS["{{AUTHOR}}"]="张三"
REPLACEMENTS["{{VERSION}}"]="1.0.0"
# 创建输出目录
mkdir -p "$OUTPUT_DIR"
# 批量处理函数
process_file() {
    local input_file="$1"
    local output_file="$2"
    local filename=$(basename "$input_file")
    echo "处理文件: $filename"
    # 读取模板
    local template_content=$(cat "$TEMPLATE_FILE")
    # 读取输入文件内容
    local file_content=$(cat "$input_file")
    # 应用替换
    local processed_content="$file_content"
    for key in "${!REPLACEMENTS[@]}"; do
        processed_content="${processed_content//$key/${REPLACEMENTS[$key]}}"
    done
    # 写入输出文件
    echo "$processed_content" > "$output_file"
}
# 递归处理目录
process_directory() {
    local current_dir="$1"
    local output_dir="$2"
    for item in "$current_dir"/*; do
        if [[ -f "$item" ]]; then
            # 处理文件
            local relative_path="${item#$INPUT_DIR/}"
            local output_path="$output_dir/$relative_path"
            mkdir -p "$(dirname "$output_path")"
            process_file "$item" "$output_path"
        elif [[ -d "$item" ]]; then
            # 递归处理子目录
            local relative_dir="${item#$INPUT_DIR/}"
            process_directory "$item" "$output_dir/$relative_dir"
        fi
    done
}
# 执行批量转换
echo "开始批量转换..."
process_directory "$INPUT_DIR" "$OUTPUT_DIR"
echo "转换完成!"

PowerShell脚本方案(适合Windows)

# 批量Word文档模板转换脚本(Windows环境)
# 添加Word COM对象
$word = New-Object -ComObject Word.Application
$word.Visible = $false
# 配置
$inputFolder = "C:\Documents\Input"
$outputFolder = "C:\Documents\Output"
$templateFile = "C:\Templates\mytemplate.dotx"
# 替换规则
$replacements = @{
    "{{COMPANY}}" = "ABC科技有限公司"
    "{{DATE}}" = (Get-Date -Format "yyyy-MM-dd")
    "{{PROJECT}}" = "文档转换项目"
}
# 确保输出目录存在
New-Item -ItemType Directory -Force -Path $outputFolder
# 批量处理函数
function Convert-Document {
    param(
        [string]$inputPath,
        [string]$outputPath,
        [hashtable]$replacements
    )
    try {
        # 打开文档
        $doc = $word.Documents.Open($inputPath)
        # 应用替换
        foreach ($key in $replacements.Keys) {
            $find = $word.Selection.Find
            $find.Text = $key
            $find.Replacement.Text = $replacements[$key]
            $find.Forward = $true
            $find.Format = $false
            $find.MatchCase = $false
            $find.MatchWholeWord = $false
            # 执行全部替换
            $find.Execute([ref]$false, [ref]$false, [ref]$false, 
                         [ref]$false, [ref]$false, [ref]$false, 
                         [ref]$false, [ref]$false, [ref]$false, 
                         [ref]$false)
        }
        # 保存文档
        $doc.SaveAs([ref]$outputPath, [ref]16)  # 16 = wdFormatDocument
        Write-Host "已转换: $([System.IO.Path]::GetFileName($inputPath))"
    } catch {
        Write-Error "处理文件失败: $($_.Exception.Message)"
    } finally {
        # 关闭文档
        if ($doc) {
            $doc.Close()
        }
    }
}
# 遍历输入文件夹
$files = Get-ChildItem -Path $inputFolder -Filter "*.docx" -Recurse
foreach ($file in $files) {
    $relativePath = $file.FullName.Substring($inputFolder.Length + 1)
    $outputPath = Join-Path $outputFolder $relativePath
    # 创建子目录
    $outputDir = Split-Path $outputPath -Parent
    New-Item -ItemType Directory -Force -Path $outputDir | Out-Null
    # 转换文档
    Convert-Document -inputPath $file.FullName -outputPath $outputPath -replacements $replacements
}
# 清理
$word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
Write-Host "批量转换完成!"

使用Python处理多种文档格式

import os
import pandas as pd
from pathlib import Path
class MultiFormatConverter:
    """支持多种文档格式的转换器"""
    def __init__(self):
        self.supported_formats = {
            '.csv': self._convert_csv,
            '.json': self._convert_json,
            '.xml': self._convert_xml,
            '.txt': self._convert_txt,
            '.md': self._convert_md
        }
    def convert_file(self, input_path, output_path, template_data):
        """根据文件格式选择合适的转换方法"""
        ext = Path(input_path).suffix.lower()
        if ext in self.supported_formats:
            self.supported_formats[ext](input_path, output_path, template_data)
        else:
            print(f"不支持的格式: {ext}")
    def _convert_csv(self, input_path, output_path, template_data):
        """转换CSV文件"""
        df = pd.read_csv(input_path)
        # 应用模板数据
        for column in df.columns:
            if column in template_data:
                df[column] = template_data[column]
        df.to_csv(output_path, index=False)
    def _convert_json(self, input_path, output_path, template_data):
        """转换JSON文件"""
        import json
        with open(input_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        # 递归替换
        def replace_values(obj):
            if isinstance(obj, str):
                for key, value in template_data.items():
                    obj = obj.replace(key, str(value))
                return obj
            elif isinstance(obj, dict):
                return {k: replace_values(v) for k, v in obj.items()}
            elif isinstance(obj, list):
                return [replace_values(item) for item in obj]
            return obj
        data = replace_values(data)
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
    def _convert_xml(self, input_path, output_path, template_data):
        """转换XML文件"""
        import xml.etree.ElementTree as ET
        tree = ET.parse(input_path)
        root = tree.getroot()
        # 遍历并替换文本内容
        for elem in root.iter():
            if elem.text:
                for key, value in template_data.items():
                    if key in elem.text:
                        elem.text = elem.text.replace(key, str(value))
        tree.write(output_path, encoding='utf-8', xml_declaration=True)
    def _convert_txt(self, input_path, output_path, template_data):
        """转换文本文件"""
        with open(input_path, 'r', encoding='utf-8') as f:
            content = f.read()
        for key, value in template_data.items():
            content = content.replace(key, str(value))
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(content)
    def _convert_md(self, input_path, output_path, template_data):
        """转换Markdown文件"""
        self._convert_txt(input_path, output_path, template_data)
# 使用示例
def batch_conversion_example():
    converter = MultiFormatConverter()
    # 模板数据
    template_data = {
        "{{COMPANY}}": "科技公司",
        "{{DATE}}": "2024-01-15",
        "{{VERSION}}": "1.0.0"
    }
    input_dir = Path("./input_files")
    output_dir = Path("./output_files")
    output_dir.mkdir(exist_ok=True)
    # 遍历所有文件
    for file_path in input_dir.rglob("*"):
        if file_path.is_file():
            relative_path = file_path.relative_to(input_dir)
            output_path = output_dir / relative_path
            output_path.parent.mkdir(parents=True, exist_ok=True)
            converter.convert_file(
                str(file_path), 
                str(output_path), 
                template_data
            )
    print("批量转换完成!")
if __name__ == "__main__":
    batch_conversion_example()

使用建议

  1. 按需选择方案

    • 简单文本替换:Shell脚本
    • Word文档处理:Python + python-docx
    • Windows环境:PowerShell
    • 多种格式:Python综合方案
  2. 性能优化

    • 使用并行处理处理大量文件
    • 缓存模板数据
    • 使用异步IO
  3. 错误处理

    • 添加日志记录
    • 实现失败重试机制
    • 验证输出文件完整性

根据您的具体需求选择合适的方案,这些脚本都可以进一步定制和扩展。

抱歉,评论功能暂时关闭!