fix: Improve Excel file conversion with temp files and better cleanup

This commit is contained in:
Bobby Abellana (aider) 2025-02-21 11:24:11 -08:00
parent b725f52366
commit ff2500707f

View File

@ -482,14 +482,29 @@ function Convert-Files {
$workbook = $excel.Workbooks.Open($downloadPath)
Write-Host "Saving as XLSX: $xlsxPath"
# Save as XLSX (51 = xlOpenXMLWorkbook)
$workbook.SaveAs($xlsxPath, 51)
# Create a temporary filename without spaces
$tempFileName = [System.IO.Path]::GetRandomFileName() + ".xlsx"
$tempFilePath = Join-Path $env:TEMP $tempFileName
# Save to temp file first
$workbook.SaveAs([string]$tempFilePath, 51) # 51 = xlOpenXMLWorkbook
$workbook.Close($true)
Start-Sleep -Seconds 2 # Give Excel time to finish
if (-not (Test-Path -LiteralPath $xlsxPath)) {
throw "Failed to create XLSX file at: $xlsxPath"
# After Excel is closed, rename the file to the desired name
if (Test-Path -LiteralPath $tempFilePath) {
if (Test-Path -LiteralPath $xlsxPath) {
Remove-Item -LiteralPath $xlsxPath -Force
}
Move-Item -LiteralPath $tempFilePath -Destination $xlsxPath -Force
if (-not (Test-Path -LiteralPath $xlsxPath)) {
throw "Failed to rename temporary file to final XLSX file"
}
}
else {
throw "Failed to create temporary XLSX file at: $tempFilePath"
}
$script:txtStatus.Text += "Successfully converted to: $xlsxFileName`n"
@ -504,10 +519,15 @@ function Convert-Files {
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
# Kill any remaining Excel processes from this session
# Force cleanup of any remaining Excel processes
Get-Process -Name "EXCEL" -ErrorAction SilentlyContinue |
Where-Object { $_.SI -eq [System.Security.Principal.WindowsIdentity]::GetCurrent().SessionId } |
Stop-Process -Force
# Clean up temp file if it still exists
if ($tempFilePath -and (Test-Path -LiteralPath $tempFilePath)) {
Remove-Item -LiteralPath $tempFilePath -Force -ErrorAction SilentlyContinue
}
}
$script:txtStatus.Text += "Successfully converted to: $xlsxFileName`n"