1

我有一个小脚本,允许我将多个 .csv 合并到一个 .xlsx:

$path = "C:\Users\FrancescoM\Desktop\CSV\Results\*"
$csvs = Get-ChildItem $path -Include *.csv
$y = $csvs.Count
Write-Host "Detected the following CSV files: ($y)"
Write-Host " "$csvs.Name"`n"
$outputfilename = "Final Registry Results"
Write-Host Creating: $outputfilename
$excelapp = New-Object -ComObject Excel.Application
$excelapp.SheetsInNewWorkbook = $csvs.Count
$xlsx = $excelapp.Workbooks.Add()
for ($i=1; $i -le $y; $i++) {
    $worksheet = $xlsx.Worksheets.Item($i)
    $worksheet.Name = $csvs[$i-1].Name
    $file = (Import-Csv $csvs[$i-1].FullName)
    $file | ConvertTo-Csv -Delimiter "`t" -NoTypeInformation | Clip
    $worksheet.Cells.Item(1).PasteSpecial() | Out-Null
}

$output = "Results.xlsx"
$xlsx.SaveAs($output)
$excelapp.Quit()

如果我运行它一次它可以完美运行并创建我的“Results.xlsx”文件。

但是,如果我随后删除“Results.xlsx”文件并再次运行代码,则会收到此错误:

此位置已存在名为“Results.xlsx”的文件。你想更换它吗?

在此处输入图像描述

但很明显,该文件不再存在。我相信我Excel.Application以错误的方式关闭。如何正确关闭?

4

1 回答 1

1

正如 Ansgar Wiechers 评论的那样,最好为这段代码使用完整的路径和文件名,$output = "Results.xlsx"否则,输出将被写入 Excel 的当前目录,而这可能不是您期望的。

回答问题如何正确关闭 Excel.Application?,完成后不仅需要退出Excel,还需要释放代码中使用的Com对象。你这样做:

$excelapp.Quit()

# release the WorkSheet Com object
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsx) | Out-Null
# release the Excel.Application Com object
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excelapp) | Out-Null 
# Force garbage collection
[System.GC]::Collect()
# Suspend the current thread until the thread that is processing the queue of finalizers has emptied that queue.
[System.GC]::WaitForPendingFinalizers()
于 2018-11-11T10:28:40.817 回答