加速Excel PowerShell修改到文件

时间:2014-11-23 11:15:26

标签: excel powershell automation comparison

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

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

$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

1 个答案:

答案 0 :(得分:1)

在整个列上使用内置的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