refactor: Simplify Excel conversion process in SharePointFunctions.ps1
This commit is contained in:
parent
31407f0330
commit
93ffe6a5a2
@ -478,30 +478,24 @@ function Convert-Files {
|
|||||||
$excel.DisplayAlerts = $false
|
$excel.DisplayAlerts = $false
|
||||||
|
|
||||||
try {
|
try {
|
||||||
# Use proper path handling for Excel
|
Write-Host "Opening workbook: $downloadPath"
|
||||||
$workbook = $excel.Workbooks.Open([string]$downloadPath)
|
$workbook = $excel.Workbooks.Open($downloadPath)
|
||||||
|
|
||||||
# Save as XLSX using Excel constants
|
Write-Host "Saving as XLSX: $xlsxPath"
|
||||||
$xlOpenXMLWorkbook = 51 # Excel constant for XLSX format
|
# Save as XLSX (51 = xlOpenXMLWorkbook)
|
||||||
|
$workbook.SaveAs($xlsxPath, 51)
|
||||||
# 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)
|
|
||||||
$workbook.Close($true)
|
$workbook.Close($true)
|
||||||
|
|
||||||
# After Excel is closed, copy the file to the desired location
|
Start-Sleep -Seconds 2 # Give Excel time to finish
|
||||||
if (Test-Path -LiteralPath $tempXlsxPath) {
|
|
||||||
Copy-Item -LiteralPath $tempXlsxPath -Destination $xlsxPath -Force
|
if (-not (Test-Path -LiteralPath $xlsxPath)) {
|
||||||
Remove-Item -LiteralPath $tempXlsxPath -Force
|
throw "Failed to create XLSX file at: $xlsxPath"
|
||||||
}
|
|
||||||
else {
|
|
||||||
throw "Excel SaveAs failed to create temporary file"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$script:txtStatus.Text += "Successfully converted to: $xlsxFileName`n"
|
||||||
}
|
}
|
||||||
finally {
|
finally {
|
||||||
# Proper cleanup of Excel COM objects
|
# Cleanup
|
||||||
$excel.Quit()
|
$excel.Quit()
|
||||||
if ($workbook) {
|
if ($workbook) {
|
||||||
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
|
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
|
||||||
@ -510,7 +504,7 @@ function Convert-Files {
|
|||||||
[System.GC]::Collect()
|
[System.GC]::Collect()
|
||||||
[System.GC]::WaitForPendingFinalizers()
|
[System.GC]::WaitForPendingFinalizers()
|
||||||
|
|
||||||
# Force Excel process cleanup
|
# Kill any remaining Excel processes from this session
|
||||||
Get-Process -Name "EXCEL" -ErrorAction SilentlyContinue |
|
Get-Process -Name "EXCEL" -ErrorAction SilentlyContinue |
|
||||||
Where-Object { $_.SI -eq [System.Security.Principal.WindowsIdentity]::GetCurrent().SessionId } |
|
Where-Object { $_.SI -eq [System.Security.Principal.WindowsIdentity]::GetCurrent().SessionId } |
|
||||||
Stop-Process -Force
|
Stop-Process -Force
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user