更改Excel图表中条形的颜色

时间:2019-10-22 13:00:45

标签: powershell

我写了下面的代码来获取excel条形图。但是所有条形的颜色都变为蓝色。

$file = 'D:\Uptime_Last Week.xlsx'
$workbook = $xl.Workbooks.Open($file)
$sheet = $workbook.Worksheets.item(1)

$objCharts = $sheet.ChartObjects()
$objChart = $objCharts.Add(500, 500, 500, 500)

$dataRange = $sheet.range("A1:B5")
$ColumnCount = $sheet.Columns
$chart=$sheet.Shapes.AddChart().Chart

$chart.seriesCollection(1).Select() | Out-Null
$chart.SeriesCollection(1).ApplyDataLabels() | out-Null
$objChart.Chart.SetSourceData($dataRange)

请让我知道如何更改颜色。 以下是我的数据

Name    Avg
Network 99.99716242
Unix    99.98140079
Windows 99.84750824
storage 100

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

Add-Type -AssemblyName Microsoft.Office.Interop.Excel

$file = 'D:\Uptime_Last Week.xlsx'

$excel               = New-Object -ComObject Excel.Application
$excel.Visible       = $true
$excel.DisplayAlerts = $false 

$workbook            = $excel.Workbooks.Open( $file, [System.Type]::Missing, $false ) 
$sheet               = $workbook.Worksheets.item(1)

$objCharts = $sheet.ChartObjects()
$objChart  = $objCharts.Add(500, 500, 500, 500)

$dataRange   = $sheet.Range("A1:B5")
$ColumnCount = $sheet.Columns
$chart       = $sheet.Shapes.AddChart().Chart

# color each bar

$chart.SeriesCollection(1).Points(1).Interior.Color = 255
$chart.SeriesCollection(1).Points(2).Interior.Color = 255 * 255
$chart.SeriesCollection(1).Points(3).Interior.Color = 255 * 255 * 255
$chart.SeriesCollection(1).Points(4).Interior.Color = 0

[void]$chart.SeriesCollection(1).ApplyDataLabels() 
[void]$objChart.Chart.SetSourceData($dataRange)