LoginSignup
0
3

More than 3 years have passed since last update.

PowerShellで、csvの情報を元に各種Excelファイルの特定セルの入力を行いたい

Posted at

前回の続きになります。
CSVにあるファイルパス、シート名、行列、及び値/数式の情報を、対象位置に記載して保存していくスクリプトです。

テスト仕様書とか設計書とかで表記揺れを修正するときに使ったりしていました。
表記なんて揺れてもいいじゃん、そういうのがやりたいんじゃないんだ。

updateExcel.ps1
Param(
    $targetCsv ,
    [ValidateSet("Value2","Formula")]$updateTarget
)

if($targetCsv -eq $null) {
    '-targetCsv オプションを指定して、処理対象のCSVファイルを指定してください。'
    return
}

if($updateTarget -eq $null) {
    '-updateTarget オプションを指定して、CSVから書き換える項目を指定してください'
    return
}

if((Test-Path $targetCsv) -eq $false) {
    "$targetCsv ファイルが見つかりません。"
    return
}

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false

$csv = Import-Csv $targetCsv -Encoding Default

$csv | ForEach-Object {
    $fullName = $_.FullName
    $sheetName = $_.SheetName
    [int32]$Column = $_.Column
    [int32]$Row = $_.Row

    if($updateTarget -eq "Value2") {
        $targetText = $_.Value2
    } elseif($updateTarget -eq "Formula") {
        $targetText = $_.Formula
    }

    $fileOpen = $true

    try {
        $workBook = $excel.Workbooks.open($fullName)
    } catch {
        Write-Host "$fullName のオープンに失敗しました。このファイルに対する処理はスキップします。" -ForegroundColor Red
        $fileOpen = $false
    }

    $sheet = $workBook.sheets($sheetName)

    if($fileOpen -eq $true) {
        if($updateTarget -eq "Value2") {
            if($(($sheet.Cells($Row,$Column)).Value2) -ne $targetText) {
                ($sheet.Cells($Row,$Column)).Value2 = $targetText
                [void]$workBook.save()
            }
        } elseif($updateTarget -eq "Formula") {
            $sheet = $workBook.Sheets($sheetName)
            if($(($sheet.Cells($Row,$Column)).Formula) -ne $targetText) {
                ($sheet.Cells($Row,$Column)).Formula = $targetText
                [void]$workBook.save()
            }
        }
        [void]$workBook.close()
    }
}

$sheet = $null
$excel.quit()

targetCsvとして、前回作成したCsvファイルを
加工したものを指定します。(検索を仕掛けて、セルの情報と値/数式を取得したのが前回のCsv)
不要な行は削除しても良いです。

updateTargetとして、Value2(値)か、Formula(数式)かを選択します。
数式の方はちょっと面倒で、エクセルでCsvを編集して保存すると自動で値に書き換えてくれちゃいますので、
テキストエディタで編集する感じになりますが、エクセルを経由しないと数式が正しいかの検証ができないので、
いろいろ神経質なやり方で編集する感じになります。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3