From 93ffe6a5a2015721aa73f3cb7f2ad22d9aa18066 Mon Sep 17 00:00:00 2001 From: "Bobby Abellana (aider)" Date: Fri, 21 Feb 2025 11:11:37 -0800 Subject: [PATCH] refactor: Simplify Excel conversion process in SharePointFunctions.ps1 --- SharePointFunctions.ps1 | 32 +++++++++++++------------------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/SharePointFunctions.ps1 b/SharePointFunctions.ps1 index 14ac83b..7b5e5b7 100644 --- a/SharePointFunctions.ps1 +++ b/SharePointFunctions.ps1 @@ -478,30 +478,24 @@ function Convert-Files { $excel.DisplayAlerts = $false try { - # Use proper path handling for Excel - $workbook = $excel.Workbooks.Open([string]$downloadPath) + Write-Host "Opening workbook: $downloadPath" + $workbook = $excel.Workbooks.Open($downloadPath) - # Save as XLSX using Excel constants - $xlOpenXMLWorkbook = 51 # Excel constant for XLSX format - - # Create a temporary filename without spaces - $tempXlsxPath = Join-Path $env:TEMP ([System.IO.Path]::GetRandomFileName() + ".xlsx") - - # Save to temporary file first - $workbook.SaveAs([string]$tempXlsxPath, $xlOpenXMLWorkbook) + Write-Host "Saving as XLSX: $xlsxPath" + # Save as XLSX (51 = xlOpenXMLWorkbook) + $workbook.SaveAs($xlsxPath, 51) $workbook.Close($true) - # After Excel is closed, copy the file to the desired location - if (Test-Path -LiteralPath $tempXlsxPath) { - Copy-Item -LiteralPath $tempXlsxPath -Destination $xlsxPath -Force - Remove-Item -LiteralPath $tempXlsxPath -Force - } - else { - throw "Excel SaveAs failed to create temporary file" + Start-Sleep -Seconds 2 # Give Excel time to finish + + if (-not (Test-Path -LiteralPath $xlsxPath)) { + throw "Failed to create XLSX file at: $xlsxPath" } + + $script:txtStatus.Text += "Successfully converted to: $xlsxFileName`n" } finally { - # Proper cleanup of Excel COM objects + # Cleanup $excel.Quit() if ($workbook) { [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null @@ -510,7 +504,7 @@ function Convert-Files { [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() - # Force Excel process cleanup + # Kill any remaining Excel processes from this session Get-Process -Name "EXCEL" -ErrorAction SilentlyContinue | Where-Object { $_.SI -eq [System.Security.Principal.WindowsIdentity]::GetCurrent().SessionId } | Stop-Process -Force