尝试使用PowerShell在Excel中添加图表。我使用以下链接获取指导:
以下是代码:
# <---- 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 -------------------------------------->
这适用于我使用Excel 2010的一台计算机,但在另一台使用Excel 2003的计算机上,它失败并显示以下消息:
“方法调用失败,因为[System .__ ComObject]不包含名为'addchart'的方法。”
这是我正在使用的Excel版本的限制吗?使用PowerShell,如何在Excel 2003的工作表中添加图表?
答案 0 :(得分:1)
根据documentation方法已添加Excel 2007,因此它在Excel 2003中不可用。尝试将图表创建记录为Excel 2003中的宏并将结果转换为PowerShell。你可能会得到这样的东西:
$chart = $xl.Charts.Add
$chart.ChartType = ...
$chart.SetSourceData $xl.Sheets(1).Range(...), ...
$chart.Location ...