0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

大量のExcelファイルから文字だけ抽出して1つのテキストファイルにするPowerShell

Last updated at Posted at 2021-06-02

私の職場はExcelで書かれた仕様書が飛び交っていて、しかも機能単位でファイルが分かれていたりするので、あの値はどこで使われるんだっけ?といったことを調べるために、いちいちExcelを開くのが面倒でしょうがない。

というわけでPowerShellで特定のフォルダに保存したExcelを片っ端からスキャンして、1つのテキストファイルにするPowerShellを書いた。類似のVBAマクロやツールはあるが、私としては、どこに書かれてるかを検索できるインデックスが欲しかったので、これぐらいの機能がちょうどいい。

$path = (Convert-Path .) + "\target\*.xls*"
$outFname = (Convert-Path .) + "\out.txt"

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

Get-ChildItem -Path $path | ForEach-Object {
    $book = $excel.Workbooks.open($_.FullName)
    $bookname = $_.FullName
    echo $bookname
    $book.Worksheets | ForEach-Object{
        $temp = ""
        $sheetname = $_.Name
        echo $sheetname
        $range = $_.UsedRange
        $range | ForEach-Object {
            if ( -not [string]::IsNullOrEmpty($_.text)){
                $temp = $temp + " " + $_.text
            }
        }
        $temp = $temp -replace "`r`n"," "
        $temp = $temp -replace "`n"," "
        $temp = $temp -replace "`t"," "
        while($temp.Contains("  ")){
            $temp = $temp -replace "  "," "
        }
        $excel.Workbooks.Close()
        Add-Content -LiteralPath $outFname -Value ($bookname+",",$sheetname+","+$temp)
    }
}
$excel.Quit()
$excel = $null
[System.GC]::Collect()

実行してみるとわかるが、なかなか時間がかかる。ソースコード中でRange("A1","Z1000")と書いている個所を書き換えることで調整できるが、もうちょっと工夫できるかもしれない。

Range("A1","Z1000")と書いていた個所をUsedRangeに書き換えました。

0
1
2

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?