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