Created
January 9, 2026 13:32
-
-
Save eugrus/e75542f060adc54a9e9b7dc4f3084856 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| param( | |
| [string]$filePath | |
| ) | |
| $filePath = Resolve-Path -Path $filePath | |
| if (-not (Test-Path $filePath)) { | |
| Write-Error "File does not exist: $filePath" | |
| exit 1 | |
| } | |
| $excel = New-Object -ComObject Excel.Application | |
| $excel.Visible = $false | |
| $excel.DisplayAlerts = $false | |
| $workbook = $excel.Workbooks.Open($filePath) | |
| $worksheet = $workbook.Worksheets.Item(1) | |
| $usedRange = $worksheet.UsedRange | |
| $rowCount = $usedRange.Rows.Count | |
| $colCount = $usedRange.Columns.Count | |
| # Read all data first, trim but preserve internal spacing | |
| $data = @() | |
| for ($row = 1; $row -le $rowCount; $row++) { | |
| $rowData = @() | |
| for ($col = 1; $col -le $colCount; $col++) { | |
| $text = $usedRange.Cells.Item($row, $col).Text | |
| $text = ($text -replace '\s+$', '') -replace '\|', '\|' | |
| $rowData += $text | |
| } | |
| $data += ,$rowData | |
| } | |
| # Remove completely empty columns | |
| $validColumns = @() | |
| for ($col = 0; $col -lt $colCount; $col++) { | |
| foreach ($row in $data) { | |
| if ($row[$col] -ne "") { | |
| $validColumns += $col | |
| break | |
| } | |
| } | |
| } | |
| # Calculate max width per column | |
| $widths = @{} | |
| foreach ($col in $validColumns) { | |
| $widths[$col] = ($data | ForEach-Object { $_[$col].Length } | Measure-Object -Maximum).Maximum | |
| } | |
| # Build output | |
| $lines = @() | |
| foreach ($row in $data) { | |
| $cells = foreach ($col in $validColumns) { | |
| $row[$col].PadRight($widths[$col]) | |
| } | |
| $lines += "| " + ($cells -join " | ") + " |" | |
| } | |
| $workbook.Close($false) | |
| $excel.Quit() | |
| [System.Runtime.InteropServices.Marshal]::ReleaseComObject($worksheet) | Out-Null | |
| [System.Runtime.InteropServices.Marshal]::ReleaseComObject($workbook) | Out-Null | |
| [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null | |
| [GC]::Collect() | |
| [GC]::WaitForPendingFinalizers() | |
| Write-Output $lines |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment