[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$Path, [string]$OutDir = (Join-Path (Get-Location) 'charts'), [switch]$Force ) $ErrorActionPreference = 'Stop' $resolved = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).Path $extension = [IO.Path]::GetExtension($resolved).ToLowerInvariant() if ($extension -notin @('.xlsx', '.xlsm', '.xls')) { throw 'Поддерживаются файлы .xlsx, .xlsm и .xls' } if (-not (Test-Path -LiteralPath $OutDir)) { New-Item -ItemType Directory -Path $OutDir -Force | Out-Null } $outRoot = (Resolve-Path -LiteralPath $OutDir).Path $excel = $null $workbook = $null try { try { $excel = New-Object -ComObject Excel.Application } catch { throw 'Excel не найден. Установите настольный Microsoft Excel.' } $excel.Visible = $false $excel.DisplayAlerts = $false $workbook = $excel.Workbooks.Open($resolved, 0, $true) $saved = 0 $skipped = 0 foreach ($sheet in $workbook.Worksheets) { $sheetName = $sheet.Name -replace '[^\w\-]+', '_' foreach ($chartObject in $sheet.ChartObjects()) { $chartName = $chartObject.Name -replace '[^\w\-]+', '_' $target = Join-Path $outRoot ("{0}_{1}.png" -f $sheetName, $chartName) if ((Test-Path -LiteralPath $target) -and -not $Force) { Write-Host "Пропуск, уже существует: $target" $skipped++ continue } [void]$chartObject.Chart.Export($target, 'PNG') if (Test-Path -LiteralPath $target) { Write-Host "Готово: $target" $saved++ } } } $index = 0 foreach ($chartSheet in $workbook.Charts) { $index++ $name = $chartSheet.Name -replace '[^\w\-]+', '_' $target = Join-Path $outRoot ("chart_sheet_{0:00}_{1}.png" -f $index, $name) if ((Test-Path -LiteralPath $target) -and -not $Force) { Write-Host "Пропуск, уже существует: $target" $skipped++ continue } [void]$chartSheet.Export($target, 'PNG') if (Test-Path -LiteralPath $target) { Write-Host "Готово: $target" $saved++ } } Write-Host "Сохранено диаграмм: $saved, пропущено: $skipped" } finally { if ($workbook) { $workbook.Close($false) } if ($excel) { $excel.Quit() } if ($workbook) { [void][Runtime.InteropServices.Marshal]::ReleaseComObject($workbook) } if ($excel) { [void][Runtime.InteropServices.Marshal]::ReleaseComObject($excel) } [GC]::Collect() }