使用Powershell编辑和保存DOCX

问题描述 投票:0回答:1

我为使用DOCX文件所做的工作已稍加修改this PowerShell script,但想就地编辑DOCX文件。

[运行脚本后,终端显示错误消息:“您不能在空值表达式上调用方法”,参考第43行,$document.Save()

我不确定错误的原因,因为$document的路径已经在脚本的前面定义了。我想念什么?

这是整个脚本:

    Param ([string]$path = $(throw "-path is required."))

    Import-Module "C:\scripts\PSGenericMethods.psm1"
    [System.Reflection.Assembly]::LoadFrom("C:\Program Files (x86)\Open XML SDK\V2.5\lib\DocumentFormat.OpenXml.dll") | out-null

    [Reflection.Assembly]::LoadWithPartialName("DocumentFormat.OpenXml") | out-null
    [Reflection.Assembly]::LoadWithPartialName("DocumentFormat.OpenXml.Packaging") | out-null
    [Reflection.Assembly]::LoadWithPartialName("DocumentFormat.OpenXml.Wordprocessing") | out-null
    [Reflection.Assembly]::LoadWithPartialName("OpenXmlPowerTools") | out-null

    [DocumentFormat.OpenXml.Packaging.WordprocessingDocument]$document = $null
    $document = [DocumentFormat.OpenXml.Packaging.WordprocessingDocument]::Open($path, $true)

    [DocumentFormat.OpenXml.Packaging.MainDocumentPart]$MainDocumentPart = $document.MainDocumentPart

    [DocumentFormat.OpenXml.Wordprocessing.Document]$InnerDocument = $document.Document

    [DocumentFormat.OpenXml.Wordprocessing.Body]$Body = $document.Body

    [DocumentFormat.OpenXml.Wordprocessing.Paragraph]$paragraph = $document.Paragraph

    [DocumentFormat.OpenXml.Wordprocessing.ParagraphMarkRunProperties]$ParagraphMarkRunProperties = $document.ParagraphMarkRunProperties

    [DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties]$ParagraphProperties = $document.ParagraphProperties

    [DocumentFormat.OpenXml.Wordprocessing.ParagraphStyleId]$ParagraphStyleId = $document.ParagraphStyleId

    [DocumentFormat.OpenXml.Wordprocessing.Run]$run = $document.Run

    $paragraphs = Invoke-GenericMethod -InputObject $MainDocumentPart.Document -MethodName Descendants -GenericType DocumentFormat.OpenXml.Wordprocessing.Paragraph

    $runs = Invoke-GenericMethod -InputObject $MainDocumentPart.Document -MethodName Descendants -GenericType DocumentFormat.OpenXml.Wordprocessing.Run

    foreach ($run in $runs) { 
     if ($run.RunProperties.Languages.Val) {

    <#[String]$value = $run.InnerText#>
    [String]$language = $run.RunProperties.Languages.Val

    '{{$span xml:lang="{0}"$}}{1}{{$/span}}$' -f $language, $run.InnerText
    }
    }
    $document.close()

更新:修改脚本后,我现在不再遇到“您无法在空值表达式上调用方法”错误的问题。问题是我不确定如何将结果保存到文件中。

这可能是this thread的副本。

谁能建议一种将更改保存到文件的方法吗?

powershell openxml docx
1个回答
1
投票
[DocumentFormat.OpenXml.Wordprocessing.Document]$Document = $document.Document

因为$Document$document是相同的变量。]​​>

© www.soinside.com 2019 - 2024. All rights reserved.