在没有安装MS Word的情况下,如何使用现有dotx模板文件以编程方式更新现有docx?

2024-10-02 08:16:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在尝试用一个只有徽标的现有dotx模板文件更新一个现有docx文件(其中已经有内容)时遇到了一些问题,字体颜色和字体大小等。我已经使用MS Word Com对象创建了一个powershell脚本来完成这项工作,但不幸的是,如果没有安装MS Word,那么脚本将无法工作

Powershell脚本:

    $word=New-Object -ComObject Word.Application
    $word2=New-Object -ComObject Word.Application
    $word.Visible=$false
    $word2.Visible=$false
    
    $path="C:\test_stuff\"
    $input_file = "C:\test_stuff\features.docx"
    $output_file = "C:\test_stuff\test_file.docx"
    
    try {
        $wordopen=$word.Documents.Open($input_file)
        $newdoc = Join-Path -Path $path -childPath "my_template.dotx"
        # Create new docx from template
        $wordopen2=$word2.Documents.Add($newdoc)
        #copy data from opened docx
        $range = $wordopen.Range()
        $copy = $range.Copy()
        # paste data to newly created docx
        $range2 = $wordopen2.Range()
        $range2.Paste($copy)
        # Save
        $wordopen2.SaveAs($output_file, [Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatDocumentDefault)
        $wordopen2.Close()
        $wordopen.Close()
    }
    catch { "An error occurred." }

有没有一种方法可以在Powershell或Python中实现这一点而无需安装MS Word


Tags: 文件test脚本wordfilemscopydocx

热门问题