refactor: Improve Excel COM object handling with try-finally and GC cleanup
This commit is contained in:
parent
a5057f2a0d
commit
3a2cb289db
@ -443,21 +443,29 @@ 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
|
||||||
$workbook = $excel.Workbooks.Open($downloadPath)
|
$excel.DisplayAlerts = $false # Suppress Excel alerts
|
||||||
|
|
||||||
# Save as XLSX
|
try {
|
||||||
$workbook.SaveAs($xlsxPath, 51) # 51 is the code for XLSX format
|
$workbook = $excel.Workbooks.Open($downloadPath)
|
||||||
$workbook.Close()
|
|
||||||
$excel.Quit()
|
# Save as XLSX
|
||||||
|
$workbook.SaveAs($xlsxPath, 51) # 51 = xlOpenXMLWorkbook (*.xlsx)
|
||||||
# Clean up COM objects
|
$workbook.Close($false)
|
||||||
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
|
}
|
||||||
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($workbook) | Out-Null
|
finally {
|
||||||
Remove-Variable excel, workbook
|
# 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"
|
$script:txtStatus.Text += "Successfully converted to: $xlsxFileName`n"
|
||||||
}
|
}
|
||||||
catch {
|
catch {
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user