加快Excel PowerShell修改文件

我有一个过程,它将在单元格中查找一个值,并将其与一个数组进行比较,然后它将使用第二个数组中的相应值replace该值。

这个脚本正在工作,但我正在研究如何调整它,并使其快速。

$ColorCodes = "001", "002", "003" $FAColors = "Blue", "Red", "White" $XLSXDoc = "c:\Users\w0517\Desktop\ColorCodes.xlsx" $SheetName = "Sheet1" $Excel = New-Object -ComObject "Excel.Application" $Workbook = $Excel.workbooks.open($XLSXDoc) $Sheet = $Workbook.Worksheets.Item($SheetName) $WriteData = $Excel.WorkSheets.Item($SheetName) $RowCount = ($Sheet.usedRange.rows).count write-host The Excel Sheet Has $RowCount Rows For ($J=2; $J -le $RowCount; $J++) { $MainColor = $Sheet.Cells.Item("$J",2).Text $ArrayIndex = [array]::IndexOf($FAColors, $MainColor) $WriteData.Cells.Item("$J",2) = $ColorCodes[$ArrayIndex] } $Excel.Visible = $true 

在整个列上使用内置的Replace()方法比单独更改每个单元要快得多。

 $colors = @{ 'Blue' = "'001" 'Red' = "'002" 'White' = "'003" } $wbName = 'C:\Users\w0517\Desktop\ColorCodes.xlsx' $wsName = 'Sheet1' $xl = New-Object -COM 'Excel.Application' $wb = $xl.Workbooks.Open($wbName) $ws = $wb.Worksheets.Item($wsName) $colors.Keys | % { $ws.Cells.Item(1,2).EntireColumn.Replace($_, $colors[$_]) } $xl.Visible = $true