【PowerShell】Excel_Word_文字置換プログラム作成_Replace
多数のExcelやWordで文字置換したい
業務で帳票類やエビデンス、社内情報のExcelファイルが大量にある中で、会社名が変更されるとか名称が変更されるなどのタイミングで全部のExcelファイルを変更しなければならない業務が降ってきます。
一つ一つファイルを開いて、文字変更して、保存して閉じる。
の繰り返し作業を延々とやり続けなければなりません。
「文字列を一括で変更できないか。」
それでは、PowerShellで作成してみようと思い、作成しましたので、ご紹介します。
ご自由に参考にしてくれれば、幸いです。
Powershell実行ファイルps1
では、早速ですが、ソースコードを載せます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 |
<# Excel_Word_Replace.ps1 対象フォルダ名 [検索文字列] [置換文字列]#> param([String]$Dir, [String]$OldStr = "あいうABC123", [String]$NewStr = "日本Japan!!★" ) #-----------Function------------- Function Replace { [CmdletBinding(PositionalBinding=$False)] param([parameter(Position=0)][String]$Dir, [parameter(Position=1)][String]$OldStr, [parameter(Position=2)][String]$NewStr, [Alias("s")][String]$sheet = "*", #シートの名前。全シートを対象とする場合は "*" [Alias("r")][String]$range = "*", #セルの範囲("A1:C4"など).全セルを対象とする場合は "*" [Alias("a")][Int]$LookAt = 2, #セル内容が完全に同一であるものを検索 1:する 2:しない [Alias("c")][Int]$MatchCase = 0, #大文字と小文字の区別 0:しない 1:する [Alias("b")][Int]$MatchByte = 0 #半角と全角の区別 0:しない 1:する ) if (-not $Dir) { Write-Host "対象フォルダが指定されていません。処理を終了します。" -Fore Red return } if (-not (Test-Path -LiteralPath $Dir -PathType Container)) { Write-Host "対象フォルダがありません。処理を終了します。" -Fore Red return } $srcdir = Convert-Path -LiteralPath $Dir $dstdir = $srcdir + "_new" if (Test-Path -LiteralPath $dstdir) { Write-Host "$($dstdir)が上書きされます。続行しますか。y/n [n]:" -Fore Yellow -NoNewline $answer = "" try { $answer = (Read-Host).Trim().ToUpper() } catch {} switch ($answer) { "y" { Remove-Item -LiteralPath $dstdir -Recurse -Force } default { Write-Host "処理を終了します。" -Fore Red; return } } } New-Item $dstdir -ItemType Directory | Out-Null Add-Type -AssemblyName Microsoft.Office.Interop.Excel Write-Host "Excelファイル処理を開始します。" try { $excel = New-Object -ComObject Excel.Application $excel.Visible = $false $excel.DisplayAlerts = $false $xlFomulas = [Microsoft.Office.Interop.Excel.XlFindLookIn]::xlFormulas #$xlValues = [Microsoft.Office.Interop.Excel.XlFindLookIn]::xlValues $default = [Type]::Missing $num_files = 0 #$shape = [Microsoft.Office.Interop.Excel.Shape]::shape #フィルターした全てのファイルに対して1ファイルずつ Get-ChildItem -LiteralPath $srcdir -Filter "*.xls*" -Recurse | % { $srcfile = $_.FullName Write-Host "$srcfile : " -NoNewline $workbook = $excel.Workbooks.Open($srcfile) $found = $false #ExceSheet 1シートずつ $workbook.Sheets | % { $worksheet = $_ if ($sheet -ne "*" -and $sheet -ne $worksheet.Name) { Return } if ($range -eq "*") { $range1 = $worksheet.Cells $shape1 = $worksheet.Shapes $pagesetup1 = $worksheet.pageSetup } else { $range1 = $worksheet.Range($range) } #セル全体検索Find $result = $range1.Find($OldStr, # What $default, # After $xlFomulas, # LookIn $LookAt, # LookAt $default, # SearthOrder $default, # SearchDirection $matchCase, # MatchCase $matchByte, # MatchByte $default # SearchFormat ) if ($result) { $found = $true #セル全体置換Replace $range1.Replace($OldStr, # What $NewStr, # Replacement $LookAt, # LookAt $default, # SearthOrder $matchCase, # MatchCase $matchByte, # MatchByte $default, # SearchFormat $default # ReplaceFormat ) | Out-Null } #テキストボックス内の置換 if ($shape1.Count -gt 0) { $found = $true Foreach($shapeitem in $shape1) { if ($shapeitem.TextFrame2.HasText) { $shapeText = $shapeitem.TextFrame2.TextRange.Text if ($shapeText.Contains($OldStr)) { $resultstr = $shapeText.Replace($OldStr, $NewStr) $shapeitem.TextFrame2.TextRange.Text = "$resultstr" } } } } #センターフッター置換 if ($pagesetup1.CenterFooter -ne "*") { $found = $true $centerfooterText = $pagesetup1.CenterFooter if ($centerfooterText.Contains($OldStr)) { $resultstr = $centerfooterText.Replace($OldStr, $NewStr) $pagesetup1.CenterFooter = "$resultstr" } } #センターヘッダー置換 if ($pagesetup1.CenterHeader -ne "*") { $found = $true $centerheaderText = $pagesetup1.CenterHeader if ($centerheaderText.Contains($OldStr)) { $resultstr = $centerheaderText.Replace($OldStr, $NewStr) $pagesetup1.CenterHeader = "$resultstr" } } #左フッター置換 if ($pagesetup1.LeftFooter -ne "*") { $found = $true $leftfooterText = $pagesetup1.LeftFooter if ($leftfooterText.Contains($OldStr)) { $resultstr = $leftfooterText.Replace($OldStr, $NewStr) $pagesetup1.LeftFooter = "$resultstr" } } #左ヘッダー置換 if ($pagesetup1.LeftHeader -ne "*") { $found = $true $leftheaderText = $pagesetup1.LeftHeader if ($leftheaderText.Contains($OldStr)) { $resultstr = $leftheaderText.Replace($OldStr, $NewStr) $pagesetup1.LeftHeader = "$resultstr" } } #右フッター置換 if ($pagesetup1.RightFooter -ne "*") { $found = $true $rightfooterText = $pagesetup1.RightFooter if ($rightfooterText.Contains($OldStr)) { $resultstr = $rightfooterText.Replace($OldStr, $NewStr) $pagesetup1.RightFooter = "$resultstr" } } #右ヘッダー置換 if ($pagesetup1.RightHeader -ne "*") { $found = $true $rightheaderText = $pagesetup1.RightHeader if ($rightheaderText.Contains($OldStr)) { $resultstr = $rightheaderText.Replace($OldStr, $NewStr) $pagesetup1.RightHeader = "$resultstr" } } } #新しいファイルパス名に置換 $newfile = $srcfile.Replace($srcdir,$dstdir) if ($found -and $srcfile -ne $newfile) { $num_files++ Write-Host "置換あり" -Fore Green $dstsubdir = Split-Path $newfile -Parent if (-not (Test-Path -LiteralPath $dstsubdir -PathType Container)) { New-Item $dstsubdir -ItemType Directory | Out-Null } #名前を付けて保存 $workbook.SaveAs($newfile) } else{ Write-Host "置換なし" } $workbook.Close() } Write-Host "Excelファイル処理が終了しました。" Write-Host "$num_files ファイルの置換を行ないました。" } catch { Write-Host $Error[0].ToString() $Error[0].InvocationInfo.PositionMessage } finally { if ($excel) { $excel.Quit() } $result,$range1,$shape1,$pagesetup1,$worksheet,$workbook,$excel | % { try{[Runtime.Interopservices.Marshal]::ReleaseComObject($_)}catch{}; $_ = $Null } | Out-Null [GC]::Collect() } #------------------【Word】----------------------- #---WdFindWrap定数--- #wdFindStop 0 検索範囲の先頭または末尾まで検索したら、検索を終了します。 $wdFindContinue = 1 #検索範囲の先頭または末尾まで検索しさらに検索を続ける #wdFindAsk 2 選択範囲または指定範囲を検索し、文書の残りの部分も検索するかどうかをたずねるメッセージを表示します。 #wdFindContinue 1 検索範囲の先頭または末尾まで検索し、さらに検索を続けます。 #---WdReplace定数--- #$wdReplaceNone = 0 # 置換を行わない #$wdReplaceOne = 1 #最初に一致したものを置換する $wdReplaceAll = 2 #すべて置換する # パラメーター $findText = [parameter(Position=1)][String]$OldStr #検索する文字列 $matchCase = $false #大文字小文字の区別する $matchWholeWord = $false #完全に一致する単語だけを検索する $matchWildcards = $false #ワイルドカードを使用する $matchSoundsLike = $false #あいまい検索 $matchAllWordForms = $false #すべての単語の活用形を検索する $forward = $true #検索方向(Trueで末尾へ) $wrap = $wdFindContinue #検索が文書の末尾に達した場合にどうするか(WdFindWrap定数) $format = $false #書式を検索する場合 $replaceWith = [parameter(Position=2)][String]$NewStr #置換文字列 $replace = $wdReplaceAll #置換する文字列の個数(Wdreplace 定数)その他 : wdReplaceNone 置換しない wdReplaceOne 最初のみ置換 $matchKashida = $false $matchdiacritics = $false $matchalefhamza = $false $matchControl = $true Add-Type -AssemblyName Microsoft.Office.Interop.Word Write-Host "Wordファイル処理を開始します。" try { $word = New-Object -ComObject Word.Application # アプリ起動 $word.Visible = $false # 画面非表示 #$word.DisplayAlerts = $false # 画面アラート無効 $default = [Type]::Missing $num_files = 0 #フィルターした全てのファイルに対して1ファイルずつ Get-ChildItem -LiteralPath $srcdir -Filter "*.doc*" -Recurse | % { $srcfile = $_.FullName Write-Host "$srcfile : " -NoNewline $doc = $word.Documents.Open($srcfile) $shape1 = $doc.Shapes $found = $false $findObject = $word.Selection.Find #検索書式クリア $findObject.ClearFormatting() $findObject.Replacement.ClearFormatting() $resultreplace = $false #置換処理実行 $resultreplace = $findObject.Execute($findText, $matchCase, $matchWholeWord, $matchWildcards, $matchSoundsLike, $matchAllWordForms, $forward, $wrap, $format, $replaceWith, $replace, $matchKashida, $matchdiacritics, $matchalefhamza, $matchControl) if ($resultreplace){ $found=$true } #テキストボックス内の置換 if ($shape1.Count -gt 0) { $found = $true Foreach($shapeitem in $shape1) { if ($shapeitem.TextFrame.HasText) { $shapeText = $shapeitem.TextFrame.TextRange.Text if ($shapeText.Contains($OldStr)) { $resultstr = $shapeText.Replace($OldStr, $NewStr) $shapeitem.TextFrame.TextRange.Text = "$resultstr" } } } } #ヘッダーフッターの文字置換 ForEach($sec In $doc.Sections) { #セクションの数だけループ処理 #ヘッダー置換 ForEach($hdr In $sec.Headers){ if ($hdr.Range.Text -ne "*") { #ヘッダーに何か文字がある場合 $found = $true $headerText = $hdr.Range.Text if ($headerText.Contains($OldStr)) { $resultstr = $headerText.Replace($OldStr, $NewStr) $hdr.Range.Text = "$resultstr" } } } #フッター置換 ForEach($ftr In $sec.Footers){ if ($ftr.Range.Text -ne "*") { #フッターに何か文字がある場合 $found = $true $footerText = $ftr.Range.Text if ($footerText.Contains($OldStr)) { $resultstr = $footerText.Replace($OldStr, $NewStr) $ftr.Range.Text = "$resultstr" } } } } #新ファイル名に置換 $newfile = $srcfile.Replace($srcdir,$dstdir) #置換文字がある場合 if ($found -and $srcfile -ne $newfile) { $num_files++ Write-Host "置換あり" -Fore Green $dstsubdir = Split-Path $newfile -Parent if (-not (Test-Path -LiteralPath $dstsubdir -PathType Container)) { New-Item $dstsubdir -ItemType Directory | Out-Null } $doc.SaveAs($newfile) } else { Write-Host "置換なし" } $doc.Close() } Write-Host "Wordファイル処理が終了しました。" Write-Host "$num_files ファイルの置換を行ないました。" } catch { Write-Host $Error[0].ToString() $Error[0].InvocationInfo.PositionMessage } finally { if ($word) { $word.Quit() } $shape1,$doc,$word | % { try{[Runtime.Interopservices.Marshal]::ReleaseComObject($_)}catch{}; $_ = $Null } | Out-Null [GC]::Collect() } } ##---------------------------------- ##----------メイン処理--------------- $TimeSpan = Measure-Command{ Replace $Dir $OldStr $NewStr } ##---------------------------------- ##---------------------------------- Write-Host "処理時間: "$TimeSpan.TotalSeconds"sec" #処理時間を表示 Write-Host "終了するには何かキーを押してください . . ." $Host.UI.RawUI.FlushInputBuffer() $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") | Out-Null ##---------------------------------- ##ps1ファイルのショートカットファイルを作成してプロパティのリンク先の先頭に以下の文を入れると、ファイルをドラッグ&ドロップできるようになる。 ##C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy RemoteSigned -File <元の文字列> ##---------------------------------- |
PowerShell実行
ショートカットからドラッグアンドドロップ
PowerShellの実行ファイルである、「ps1ファイル」のショートカット作成しておきます。
ショートカット作成することで、フォルダをドラッグアンドドロップして置換を実行できるようになるので、効率的です。

ショートカット作成したら、プロパティ画面を開いて、リンク先の先頭に
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy RemoteSigned -File
を書き足します。
そうすることで、ファイルをドラッグアンドドロップできるようになります。

コンソール画面からコマンド
ショートカット作成しないで、コンソールから実行したい場合は、
ps1ファイルのディレクトリまで移動して、<ps1ファイル名> <置換したいフォルダ> <検索文字列> <置換文字列>
で実行できます。検索文字列と、置換文字列は、ps1ファイル内でも指定できます。


フォルダ前後
実行後、置換したファイルを保存したNewフォルダが作成されますので、
置換前のフォルダと置換後のフォルダを分けることができ、置換前と比べることもできます。

ps1ファイル内から置換文字指定

ps1ファイルの先頭の方に、文字列指定するパラメーター設定を設けています。
$OldStr=”検索文字列”
$NewStr=”置換文字列”
文字を置換したいExcelWord
Excel 置換前

Excel 置換後

Word 置換前

Word 置換後
Point
- Excelファイルでは、複数シート対応
- 拡張子(.xls .xlsx .doc .docx)対応
- フォルダ階層は深くてもOK
- テキストボックス内の置換可能
- ヘッダーheader、フッターfooterの置換可能