Powershell从EXCEL创build折线图

我的powershell脚本将数据input到EXCEL工作表中

在这里输入图像描述

我正在尝试创build一个类似的折线图

在这里输入图像说明

不过,这是我迄今为止的代码:

$xlConditionValues=[Microsoft.Office.Interop.Excel.XLConditionValueTypes] $xlTheme=[Microsoft.Office.Interop.Excel.XLThemeColor] $xlChart=[Microsoft.Office.Interop.Excel.XLChartType] $xlIconSet=[Microsoft.Office.Interop.Excel.XLIconSet] $xlDirection=[Microsoft.Office.Interop.Excel.XLDirection] ... $chart=$ws.Shapes.AddChart().Chart $chart.chartType=$xlChart::xlBarClustered $start=$ws.range("A1") $Y=$ws.Range($start,$start.End($xlDirection::xlDown)) $start=$ws.range("B2") $X=$ws.Range($start,$start.End($xlDirection::xlDown)) $chartdata=$ws.Range("A$($Y.item(1).Row):A$($Y.item($Y.count).Row),B$($X.item(1).Row):B$($X.item($X.count).Row)") $chart.SetSourceData($chartdata) #add labels $chart.seriesCollection(1).Select() | Out-Null $chart.SeriesCollection(1).ApplyDataLabels() | out-Null #modify the chart title $chart.ChartTitle.Text = "Number of Computer" $ws.shapes.item("Chart 1").top=40 

这是它生成的graphics

在这里输入图像描述

我怎么才能开始解决这个问题? 任何有用的教程?

根据我对VBA的经验,看起来第一件事就是改变你的图表types。 你有$chart.chartType=$xlChart::xlBarClustered 。 基于类似的VBA命令,我会尝试将其更改为$chart.chartType=$xlChart::xlLine 。 这应该有很大的不同,让你看看还有什么需要调整的。

Degustaf是100%正确的,他是正确的答案,但是你有很多额外的东西在那里是不需要的。 我可以复制您想要的结果,包括用testing数据填充电子表格,并以比您拥有的更less的行数来完成。 在这里,检查一下,你可能会为你将来的努力带来一些指针。

 #Test Data $Data=("8/15/2014",3091),("8/14/2014",240),("8/13/2014",519),("8/12/2014",622),("8/11/2014",2132),("8/10/2014",1255),("8/9/2014",3240)|ForEach{[PSCustomObject][Ordered]@{'Date_to_Display'=$_[0];'Number_of_Computers'=$_[1]}} $xlConditionValues=[Microsoft.Office.Interop.Excel.XLConditionValueTypes] $xlTheme=[Microsoft.Office.Interop.Excel.XLThemeColor] $xlChart=[Microsoft.Office.Interop.Excel.XLChartType] $xlIconSet=[Microsoft.Office.Interop.Excel.XLIconSet] $xlDirection=[Microsoft.Office.Interop.Excel.XLDirection] $xl = new-object -ComObject Excel.Application $wb = $xl.workbooks.add() $ws = $wb.activesheet $xl.Visible = $true #Populate test data onto worksheet $Data |ConvertTo-CSV -NoTypeInformation -Delimiter "`t"| c:\windows\system32\clip.exe $ws.Range("A1").Select | Out-Null $ws.paste() $ws.UsedRange.Columns.item(1).numberformat = "dddd, mmm dd, yyyy" $ws.UsedRange.Columns.AutoFit() |Out-Null #Create Chart $chart=$ws.Shapes.AddChart().Chart $chart.chartType=$xlChart::xlLine #modify the chart title $chart.ChartTitle.Text = "Number of Computers" $ws.shapes.item("Chart 1").top=40 

如果你使用Powershell和Excel,你可能会发现$Data|ConvertTo-CSV...非常有用。

花式的东西,以避免看到不必要的红线( Exception setting "ChartType": "Unspecified error )全部:

 $chart.chartType = 4 

图表types的详细清单和更多信息可在这里: http : //learn-powershell.net/2012/12/24/powershell-and-excel-adding-a-chart-and-header-filter-to-a-report /