如何使用Powershell替换文件夹中Excel文档中所有出现的字符串

时间:2018-11-20 19:01:31

标签: excel scripting word

我能够在此处找到Word文档文件的代码,如何使用/调整同一组代码来运行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()

1 个答案:

答案 0 :(得分:0)

基于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()