Powershell脚本使用Excel运行缓慢

时间:2016-06-20 07:17:35

标签: excel csv powershell com automation

所以我有这个脚本,我在我的笔记本电脑上编码,工作得很好,工作是将两个.csv文件合并到一个.xls文件中。 使用包含几千行的两个.csv文件运行脚本最多需要几秒钟。

但是当我尝试在它应该位于的服务器上运行它时,需要......小时。我还没有完整运行,但在.xls文件中写一行可能需要2-3秒。

所以我想知道是什么导致运行时间的巨大增加。我在脚本运行时监控CPU负载,并且负载为50-60%。

服务器有大量的Ram和两个CPU核心。 我怎样才能加快速度呢?

脚本如下所示:

$path = "C:\test\*"
$path2 = "C:\test"
$date = Get-Date -Format d
$csvs = Get-ChildItem $path -Include *.csv | Sort-Object LastAccessTime -Descending | Select-Object -First 2
$y = $csvs.Count

Write-Host "Detected the following CSV files: ($y)"
foreach ($csv in $csvs) {
    Write-Host " "$csv.Name
}

$outputfilename = "regSCI " + $date
Write-Host Creating: $outputfilename

$excelapp = New-Object -ComObject Excel.Application
$excelapp.sheetsInNewWorkbook = $csvs.Count
$xlsx = $excelapp.Workbooks.Add()
$sheet = 1
$xlleft = -4131

foreach ($csv in $csvs) {
    $row = 1
    $column = 1
    $worksheet = $xlsx.Worksheets.Item($sheet)
    $worksheet.Name = $csv.Name
    $worksheet.Rows.HorizontalAlignment = $xlleft
    $file = (Get-Content $csv)
    Write-Host Worksheet created: $worksheet.Name

    foreach($line in $file) {
        Write-Host Writing Line
        $linecontents = $line -split ',(?!\s*\w+")'

        foreach($cell in $linecontents) {
            Write-Host Writing Cell
            $cell1 = $cell.Trim('"')
            $worksheet.Cells.Item($row, $column) = $cell1
            $column++
        }
        $column = 1
        $row++
        $WorkSheet.UsedRange.Columns.Autofit() | Out-Null
    }
    $sheet++
    $headerRange = $worksheet.Range("a1", "q1") 
    $headerRange.AutoFilter() | Out-Null 
}

$output = $path2 + "\" + $outputfilename
Write-Host $output
$xlsx.SaveAs($output)
$excelapp.Quit()

1 个答案:

答案 0 :(得分:2)

要加速现有代码,请在创建Excel对象后立即添加:

$excelapp.ScreenUpdating = $false
$excelapp.DisplayStatusBar = $false
$excelapp.EnableEvents = $false
$excelapp.Visible = $false

这些就在SaveAs之前:

$excelapp.ScreenUpdating = $true
$excelapp.DisplayStatusBar = $true
$excelapp.EnableEvents = $true

这导致excel不会在每次更改争议时实时渲染工作表并触发事件。如果您使应用程序不可见,则很可能DisplayStatusBarScreenUpdating无关紧要,但我将其包括在内以防万一。

此外,您在每行之后都在运行Autofit()。这肯定对性能没有帮助。