0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

画像ファイル(.png拡張子)をExcelに貼り付ける

Posted at

【PowerShell】

■はじめに

  • この記事は?
    画像ファイル(.png拡張子)をExcelに貼り付けるスクリプトを解説。

■スクリプトの概要

  • 何をするスクリプトか?
    指定したディレクトリ内のすべての画像ファイル(.png拡張子)を取得し、
    新規Excelファイルに貼り付ける。
  • どんな場面で役に立つか?
    PCの画面ショット等を取得し、それらを1つのExcelにまとめたい場合。

■動作確認環境

  • Windows 11 Pro 24H2 (OS ビルド 26100.4351)
  • PowerShell 5.1.26100.2161

■スクリプトのソースコード

excel_photo_add.ps1
#################################################################################
# excel_photo_add                       
#################################################################################
# Excelオブジェクトを生成
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true

# 新しいワークブックを作成
$workbook = $excel.Workbooks.Add()
# 新しいシートを追加
$sheet = $workbook.Worksheets.Add()
$sheet.Name = "Images"

# ユーザーにディレクトリを入力してもらう
$directoryPath = Read-Host "画像が保存されているディレクトリのパスを入力してください"

# ディレクトリ内のすべての画像ファイルを取得
$images = Get-ChildItem -Path $directoryPath -Filter *.png -Recurse

# 画像をExcelに挿入
$row = 1
foreach ($image in $images) {
    $img = $sheet.Pictures().Insert($image.FullName)
    $img.ShapeRange.LockAspectRatio = $true  # アスペクト比を維持
    $img.ShapeRange.Width = 200               # 画像の幅を設定
    $img.ShapeRange.Height = 300              # 画像の高さを設定
    $img.Top = $sheet.Cells.Item($row, 1).Top # 画像のトップ位置
    $img.Left = $sheet.Cells.Item($row, 1).Left # 画像の左位置
    $row += 17 # 次の画像のために行をスキップ
}

# ファイルパスとファイル名を設定
$savePath = "$EvidenceFolder\workbook.xlsx"

# ファイルを保存
$workbook.SaveAs($savePath)
$excel.Quit()

# スクリプト終了のメッセージ
Write-Host "画像の挿入が完了しました。Excelファイルをチェックしてください。エクスプローラーで保存ディレクトリを開きました。"
# 保存したファイルのディレクトリをエクスプローラーで開く
$folderPath = Split-Path -Path $savePath
Start-Process "explorer.exe" $folderPath

# 保存したファイルを再度開く
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$workbook = $excel.Workbooks.Open($savePath)

# スクリプト終了のメッセージ
Write-Host "画像の挿入が完了しました。Excelファイルをチェックしてください。エクスプローラーで保存ディレクトリを開きました。"
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?