PowerShell EPPlus无法更改单元格的背景颜色

时间:2018-08-03 09:48:40

标签: excel powershell epplus

我正在使用EPPlus创建Excel文档。它正在工作,但是我无法更改单元格的背景色。 我使用以下代码:

Worksheet.Cells[row,column].Style.Fill.BackgroundColor.rgb = (255,0,0)

每次执行脚本时,它都会显示:

  

“ rgb”是只读属性

当我尝试设置

Worksheet.Cells.Style.Fill.BackgroundColor = xxx

我遇到相同的错误:

  

“ BackgroundColor”是只读属性

我没有找到更多选项,您可以在其中更改颜色或将属性更改为可写... 有人有主意吗?

3 个答案:

答案 0 :(得分:0)

您可以这样设置颜色。

Worksheet.Cells[row,column].Style.Fill.PatternType = ExcelFillStyle.Solid;
Worksheet.Cells[row,column].Style.Fill.BackgroundColor.SetColor(Color.Red);

答案 1 :(得分:0)

尝试使用我的PowerShell Excel模块包装EPPlus,并使交互变得非常容易。

https://www.powershellgallery.com/packages/ImportExcel/

enter image description here

$xlfile = "$env:TEMP\test.xlsx"
rm $xlfile -ErrorAction Ignore

$pkg = ps | select company, Handles| Export-Excel $xlfile -PassThru

$ws = $pkg.Workbook.Worksheets["Sheet1"]

Set-Format -WorkSheet $ws -Range "B2:B2" -BackgroundColor Red
Set-Format -WorkSheet $ws -Range "B5:B5" -BackgroundColor Green

Close-ExcelPackage $pkg -Show

答案 2 :(得分:0)

如果要通过Add-Type将EPPlus dll直接用于​​Powershell,则可以使用以下代码

$ExcelPackage = New-Object OfficeOpenXml.ExcelPackage

$Sheet1 = $ExcelPackage.Workbook.Worksheets.Add("Sheet1")
$Sheet1.Cells["A1"].Style.Fill.PatternType = 1        # 1 denotes solid color
$Sheet1.Cells["A1"].Style.Fill.BackgroundColor.SetColor([System.Drawing.Color]::FromArgb(147,205,221))