refactor: Improve Excel COM object handling with try-finally and GC cleanup

This commit is contained in:
Bobby Abellana (aider) 2025-02-21 10:47:07 -08:00
parent a5057f2a0d
commit 3a2cb289db

View File

@ -443,21 +443,29 @@ function Convert-Files {
$xlsxFileName = $originalFileName -replace "\.xls[m]?$", ".xlsx"
$xlsxPath = "$env:TEMP\$xlsxFileName"
try {
# Open the Excel file
# Open Excel
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false # Keep Excel hidden
$workbook = $excel.Workbooks.Open($downloadPath)
# Save as XLSX
$workbook.SaveAs($xlsxPath, 51) # 51 is the code for XLSX format
$workbook.Close()
$excel.Quit()
# Clean up COM objects
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($workbook) | Out-Null
Remove-Variable excel, workbook
$excel.Visible = $false
$excel.DisplayAlerts = $false # Suppress Excel alerts
try {
$workbook = $excel.Workbooks.Open($downloadPath)
# Save as XLSX
$workbook.SaveAs($xlsxPath, 51) # 51 = xlOpenXMLWorkbook (*.xlsx)
$workbook.Close($false)
}
finally {
# Proper cleanup of Excel COM objects
$excel.Quit()
if ($workbook) {
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
}
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
$script:txtStatus.Text += "Successfully converted to: $xlsxFileName`n"
}
catch {