如何正确关闭Excel.Application?

时间:2018-11-08 20:12:08

标签: powershell csv scripting xlsx excel.application

我有一个小脚本,可以将多个.csv合并为一个.xlsx:

user_id

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

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

  

此位置已经存在一个名为“ Results.xlsx”的文件。您要更换它吗?

enter image description here

但是很明显,该文件不再存在。我相信我以错误的方式关闭了SELECT users.username, photos.photo_id, photo_likes.like_count FROM photos INNER JOIN ( SELECT photo_id, COUNT(*) AS like_count FROM likes GROUP BY photo_id ) AS photo_likes INNER JOIN users ON users.id = photos.user_id ORDER BY like_count DESC LIMIT 1 。如何将其正确关闭?

1 个答案:

答案 0 :(得分:1)

正如Ansgar Wiechers所说,最好为这段代码$output = "Results.xlsx"使用完整路径和文件名,否则,输出将被写入Excel的当前目录,并且可能不在您期望的位置。< / p>

要回答问题如何正确关闭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()