powershellではexcelを簡単に操作することができます。
基本文書
# 定数宣言
$bookPath = "G:\temp\test.xlsx"
$sheetName = "シート名"
$logSetai = 2
$start_row = 1 # 開始行
$start_col = 1 # 開始列
# 変数宣言
$username = $env:USERNAME
$hostname = hostname
$datetime = Get-Date -f 'yyyyMMddHHmmss'
$logdir = "$PSScriptRoot/log/"
$logfilename = "${username}-${hostname}-${datetime}.log"
# ログ出力開始
Start-Transcript "${logdir}${logfilename}"
try{
# logフォルダ存在の確認
if(-not (Test-Path -LiteralPath $logdir )){
New-Item $logdir -ItemType Directory
Write-Host '$logdir を作成しました。'
}
} catch [Exception]{
Write-Host '[Error] logファイルの存在を確認ください。'
Write-Host $Error
}
$book = $null
try{
# ファイルが存在するか確認
if(-not (Test-Path $bookPath)){
Write-Host "[Error] $bookPath のExcelファイルは見つかりません。`r`n 対象ファイルの存在をご確認ください。"
Exit
}else {
#Excel起動
$excel = New-Object -ComObject Excel.Application
# $excel = [System.Runtime.InteropServices.Marshal]::GetActiveObject("Excel.Application")
}
#可視化設定(通常利用時はFalse。挙動確認の際はTrue)
$excel.Visible = $True
#アラート無効化
$excel.DisplayAlerts = $False
#Excelファイル(ブック)を開く
$book = $excel.Workbooks.Open($bookPath)
#処理対象のシートを取得
$sheet = $book.Sheets($sheetName)
# 使用している行数を取得
$rows = $sheet.UsedRange.Rows.Count
# 使用している列数を取得
$cols = $sheet.UsedRange.Columns.Count
# データを取得
$tableRange = $sheet.Range($sheet.Cells.Item($start_row, $start_col), $sheet.Cells.Item($rows, $cols))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Excel 処理内容
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} catch [Exception] {
Write-Host '[Error]エラーが発生しました。'
$ErrorMessage = $_.Exception.Message
Write-Host "[Error]エラーメッセージ : $ErrorMessage"
}
finally {
# プロセスを閉じて、ガベージコレクト
if ($sheet) {
# オブジェクトの開放
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($sheet) | Out-Null
$sheet = $null
Remove-Variable sheet -ErrorAction SilentlyContinue
}
if ($book) {
# オブジェクトの開放
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($book) | Out-Null
$book = $null
Remove-Variable book -ErrorAction SilentlyContinue
}
# プロセス解放
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
[System.GC]::Collect()
if ($excel) {
#Excel終了
$excel.Quit()
# オブジェクトの開放
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
$excel = $null
Remove-Variable -Name excel -ErrorAction SilentlyContinue
# プロセス解放
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
[System.GC]::Collect()
}
}
$logfiles = Get-ChildItem -LiteralPath $logdir | Select-Object @{Name="datetimes";Expression={$_.BaseName.Substring($_.BaseName.Length - 14, 14)}} , Name |
Sort-Object -Property { $_.datetimes} -Descending
$exclude_names = ($logfiles | Select-Object -First $logSetai).Name
# 実行以外の logファイルを削除
Remove-Item "${logdir}\*" -Exclude ${exclude_names} -Recurse
Write-Host "$(Get-Date -Format g) ${exclude_names} 以外ファイルを削除"
# ログ出力終了
Stop-Transcript
Excelオブジェクトを閉じる
$excel.Quit()
$excel = $null
Quite()で終了できますが、COMオブジェクトを使っているのでオブジェクトの開放をしないとプロセスが残ってしまう不具合が発生してしまいます。
必ずガベージコレクションをしてあげましょう。
#comオブジェクトを開放
[void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($sheet)
[void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($excel)
ログイン ‹ コーポレートエンジニア — WordPress
その他
罫線
罫線の引く場所
| 名前 | 値 | 説明 |
|---|---|---|
| xlDiagonalDown | 5 | セルまたは範囲の左上から右下への斜め罫線 |
| xlDiagonalUp | 6 | セルまたは範囲の右上から左下への斜め罫線 |
| xlEdgeLeft | 7 | セルまたは範囲の左辺の罫線 |
| xlEdgeTop | 8 | セルまたは範囲の上辺の罫線 |
| xlEdgeBottom | 9 | セルまたは範囲の下辺の罫線 |
| xlEdgeRight | 10 | セルまたは範囲の右辺の罫線 |
| xlInsideVertical | 11 | 垂直の罫線を引く ※範囲選択のみ有効 |
| xlInsideHorizontal | 12 | 平行の罫線を引く ※範囲選択のみ有効 |
罫線の種類
| 名前 | 値 | 説明 |
|---|---|---|
| xlContinuous | 1 | 実線 |
| xlDash | -4115 | 破線 |
| xlDashDot | 4 | 一点鎖線 |
| xlDashDotDot | 5 | ニ点鎖線 |
| xlDot | -4118 | 点線 |
| xlDouble | -4119 | 2 本線 |
| xlLineStyleNone | -4142 | 線なし |
| xlSlantDashDot | 13 | 斜破線 |
| xlNone | 0 | 線なし |
太さの種類
| 名前 | 値 | 説明 |
|---|---|---|
| xlHairline | 1 | 細線 (最も細い罫線) |
| xlMedium | -4138 | 普通 |
| xlThick | 4 | 太線 (最も太い罫線) |
| xlThin | 2 | 極細 |


コメント