我有一个小脚本,它允许我将多个.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。怎么把它关好?
发布于 2018-11-11 10:28:40
正如Ansgar评论的那样,最好为这段代码$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()https://stackoverflow.com/questions/53215424
复制相似问题