Skip to content

Instantly share code, notes, and snippets.

@ap0llo
Created January 15, 2017 19:08
Show Gist options
  • Save ap0llo/d7d0c9edd87efff8e7db0289ee30ca10 to your computer and use it in GitHub Desktop.
Save ap0llo/d7d0c9edd87efff8e7db0289ee30ca10 to your computer and use it in GitHub Desktop.
Powershell script to export charts from excel to jpg
# Powershell script to export charts from excel to jpg
function Export-Chart($inputFile, $sheetName, $chartIndex, $outputFile)
{
# Load Powerpoint Interop Assembly
[Reflection.Assembly]::LoadWithPartialname("Microsoft.Office.Interop.Excel") > $null
[Reflection.Assembly]::LoadWithPartialname("Office") > $null
$msoFalse = [Microsoft.Office.Core.MsoTristate]::msoFalse
$msoTrue = [Microsoft.Office.Core.MsoTristate]::msoTrue
# start Excel
$application = New-Object "Microsoft.Office.Interop.Excel.ApplicationClass"
# Make sure inputFile is an absolte path
$inputFile = Resolve-Path $inputFile
$outputFile = [System.IO.Path]::GetFullPath($outputFile)
$workbook = $application.Workbooks.Open($inputFile)
$sheet = $workbook.Worksheets.Item($sheetName)
$chart = $sheet.ChartObjects($chartIndex).Chart
$chart.Export($outputFile)
$chart = $null
$sheet = $null
$workbook.Close($msoFalse)
$workbook = $null
if($application.Windows.Count -eq 0)
{
$application.Quit()
}
$application = $null
# Make sure references to COM objects are released, otherwise powerpoint might not close
# (calling the methods twice is intentional, see https://msdn.microsoft.com/en-us/library/aa679807(office.11).aspx#officeinteroperabilitych2_part2_gc)
[System.GC]::Collect();
[System.GC]::WaitForPendingFinalizers();
[System.GC]::Collect();
[System.GC]::WaitForPendingFinalizers();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment