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

PowerShell EPPlus unable to change Backgroundcolor of Cells

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

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

每次我执行脚本时它都会说:

"rgb" is a read-only property

当我尝试设置

Worksheet.Cells.Style.Fill.BackgroundColor = xxx

我得到同样的错误:

"BackgroundColor" is a read-only property

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

你这样设置颜色。

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

试试我的 PowerShell Excel 模块,它包装了 EPPlus 并使交互变得非常简单。

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

$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

如果你通过Add-Type直接在Powershell中使用EPPlus dll,那么你可以使用下面的代码

$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))