【问题标题】:How do I replace all occurrences of string in Excel documents in a folder using Powershell如何使用Powershell替换文件夹中Excel文档中所有出现的字符串
【发布时间】:2018-11-20 19:01:31
【问题描述】:

我可以在这里找到 Word 文档文件的代码,我如何使用 /adjust 同一组代码来运行 Excel 文件

谢谢

$objWord = New-Object -comobject Word.Application  
$objWord.Visible = $false

$list = Get-ChildItem "C:\Users\john\foldername\*.*" -Include *.doc*
foreach($item in $list){
$objDoc = $objWord.Documents.Open($item.FullName,$true)
$objSelection = $objWord.Selection 
$wdFindContinue = 1
$FindText = "1911" 
$MatchCase = $False 
$MatchWholeWord = $true
$MatchWildcards = $False 
$MatchSoundsLike = $False 
$MatchAllWordForms = $False 
$Forward = $True 
$Wrap = $wdFindContinue 
$Format = $False 
$wdReplaceNone = 0 
$ReplaceWith = "456" 
$wdFindContinue = 1 
$ReplaceAll = 2

$a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, ` 
$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,` 
$Wrap,$Format,$ReplaceWith,$ReplaceAll) 
$objDoc.Save()
$objDoc.Close()
}
$objWord.Quit()

【问题讨论】:

    标签: excel scripting word


    【解决方案1】:

    基于this answer,你可以这样做:

    $folderPath = "C:\Users\john\foldername\*"
    $fileType = "*.xls*"
    
    $excel = New-Object -ComObject Excel.Application  
    
    $textToReplace = @{
    # "TextToFind" = "TextToReplaceWith"
    "This1" = "That1"
    "This2" = "That2"
    "This3" = "That3"
    }
    
    Function findAndReplace($wsheet, $FindText, $ReplaceWith) {
        #simple Replace to execute on all columns of a Worksheet object
        $wsheet.Columns.Replace($FindText, $ReplaceWith) > $null
    }
    
    Function findAndReplaceMulti($wsheet, $lookupTable) {
        #apply multiple Replace on the same Worksheet object
        $lookupTable.GetEnumerator() | ForEach-Object {
            findAndReplace $wsheet $_.Key $_.Value
        }
    }
    
    Function findAndReplaceWholeWb($wbook, $lookupTable) {
        #apply multiple Replace in all Worksheets
        $wbook.Worksheets | ForEach-Object {
            findAndReplaceMulti $_ $lookupTable
        }
    }
    
    Get-ChildItem -Path $folderPath -Recurse -Filter $fileType | ForEach-Object {
        $excel.Visible = $False
        Write-Host "Processing `"$($_.Name)`"..."
        $wbook = $excel.Workbooks.Open($_.FullName)
        findAndReplaceWholeWb $wbook $textToReplace
        $wbook.Close($True)
    }
    
    $excel.Quit()
    $excel = $null
    [gc]::collect() 
    [gc]::WaitForPendingFinalizers()
    

    【讨论】:

      猜你喜欢
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      • 1970-01-01
      • 2012-04-20
      • 2023-03-15
      • 2022-06-24
      相关资源
      最近更新 更多