【发布时间】:2016-10-21 08:38:24
【问题描述】:
所以我在笔记本电脑上编写了这个脚本,它工作得很好,工作是将两个 .csv 文件合并到一个 .xls 文件中。 使用两个包含几千行的 .csv 文件运行脚本最多需要几秒钟。
但是当我尝试在它应该位于的服务器上运行它时,它需要......几个小时。我还没有完成完整的运行,但是在 .xls 文件中写入一行可能需要 2-3 秒。
所以我想知道是什么导致运行时间大幅增加。我正在监视脚本运行时的 CPU 负载,它的负载为 50-60%。
服务器有大量的内存和两个 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()
【问题讨论】:
标签: excel csv powershell com automation