0

Trying to add a chart in excel using powershell. I used the following link for guidance:

http://theolddogscriptingblog.wordpress.com/2010/07/03/how-do-i-change-the-size-or-position-of-my-chart-with-powershell/

Here is the code:

# <---- Start Code ---------------------------------------> 
$xl = New-Object -comobject Excel.Application
# Show Excel
$xl.visible = $true
$xl.DisplayAlerts = $False
# Open a workbook
$wb = $xl.workbooks.add() 
#Create Worksheets
$ws = $wb.Worksheets.Item(1) # Opens Excel and 3 empty Worksheets
1..8 | % { $ws.Cells.Item(1,$_) = $_ } # adds some data
1..8 | % { $ws.Cells.Item(2,$_) = 9-$_ } # adds some data
$range = $ws.range("a${xrow}:h$yrow") # sets the Data range we want to chart
# create and assign the chart to a variable
#$ch = $xl.charts.add() # This will open a new sheet
$ch = $ws.shapes.addChart().chart # This will put the Chart in the selected WorkSheet
$ch.chartType = 58
$ch.setSourceData($range)
$RngToCover = $ws.Range("D5:J19") # This is where we want the chart
$ChtOb = $ch.Parent # This selects the current Chart
$ChtOb.Top = $RngToCover.Top # This moves it up to row 5
$ChtOb.Left = $RngToCover.Left # and to column D 
$ChtOb.Height = $RngToCover.Height # resize This sets the height of your chart to Rows 5 - 19
$ChtOb.Width = $RngToCover.Width # resize This sets the width to Columns D - J
<------------- End Code --------------------------------------> 

This works on one machine I have which uses Excel 2010, but on another machine using Excel 2003 it fails with the following message:

"Method invocation failed because [System.__ComObject] doesn't contain a method named 'addchart'."

Is this a limitation of the version of Excel I'm using? Using powershell, how can I add a chart within a worksheet in Excel 2003?

4

1 回答 1

1

根据文档,该方法是在 Excel 2007 中添加的,因此在 Excel 2003 中不可用。尝试在 Excel 2003 中将图表创建记录为宏并将结果转换为 PowerShell。你可能会得到这样的东西:

$chart = $xl.Charts.Add
$chart.ChartType = ...
$chart.SetSourceData $xl.Sheets(1).Range(...), ...
$chart.Location ...
于 2013-03-31T23:27:55.893 回答