fix: Improve Excel file conversion with SaveAs2 and robust path handling

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

View File

@ -484,17 +484,40 @@ function Convert-Files {
$excel.DisplayAlerts = $false # Suppress Excel alerts
try {
$workbook = $excel.Workbooks.Open($downloadPath)
# Convert paths to proper format for Excel
$excelDownloadPath = $downloadPath -replace "\\", "\\"
$excelXlsxPath = $xlsxPath -replace "\\", "\\"
$workbook = $excel.Workbooks.Open($excelDownloadPath)
# Save as XLSX using Excel constants
$xlOpenXMLWorkbook = 51 # Excel constant for XLSX format
$xlNormal = 1 # Excel constant for normal save
# Use the Excel Application SaveAs2 method
$workbook.SaveAs2(
$excelXlsxPath,
$xlOpenXMLWorkbook, # FileFormat = xlsx
$null, # Password
$null, # WriteResPassword
$false, # ReadOnlyRecommended
$null, # CreateBackup
$xlNormal, # AccessMode
$null, # ConflictResolution
$true, # AddToMru
$null, # TextCodepage
$null, # TextVisualLayout
$false # Local
)
# Save as XLSX using the full path
$workbook.SaveAs([string]$xlsxPath, 51) # 51 = xlOpenXMLWorkbook (*.xlsx)
$workbook.Close($true) # True to save changes
Start-Sleep -Seconds 1 # Give Excel time to finish saving
Start-Sleep -Seconds 2 # Give Excel more time to finish saving
# Verify the file was created
if (-not (Test-Path -LiteralPath $xlsxPath)) {
throw "Excel SaveAs succeeded but file not found at: $xlsxPath"
# Verify the file was created using robust path checking
$verifyPath = [System.IO.Path]::GetFullPath($xlsxPath)
if (-not (Test-Path -LiteralPath $verifyPath)) {
throw "Excel SaveAs succeeded but file not found at: $verifyPath"
}
}
finally {
@ -506,6 +529,9 @@ function Convert-Files {
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
# Force Excel process cleanup
Get-Process -Name "EXCEL" -ErrorAction SilentlyContinue | Where-Object { $_.SI -eq [System.Security.Principal.WindowsIdentity]::GetCurrent().SessionId } | Stop-Process -Force
}
$script:txtStatus.Text += "Successfully converted to: $xlsxFileName`n"