param(
|
[Parameter(Mandatory=$true)][string]$InputRoot,
|
[Parameter(Mandatory=$true)][string]$OutputRoot,
|
[Parameter(Mandatory=$true)][string]$ManifestPath
|
)
|
|
$ErrorActionPreference = 'Stop'
|
if (-not [System.IO.Path]::IsPathRooted($OutputRoot)) { $OutputRoot = Join-Path (Get-Location).Path $OutputRoot }
|
if (-not [System.IO.Path]::IsPathRooted($ManifestPath)) { $ManifestPath = Join-Path (Get-Location).Path $ManifestPath }
|
New-Item -ItemType Directory -Force -Path $OutputRoot | Out-Null
|
$OutputRoot = (Resolve-Path -LiteralPath $OutputRoot).Path
|
$ManifestPath = [System.IO.Path]::GetFullPath($ManifestPath)
|
$before = @(Get-Process EXCEL -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Id)
|
$files = @(Get-ChildItem -LiteralPath $InputRoot -Recurse -File |
|
Where-Object { $_.Extension -ieq '.xls' -and $_.Name -match '^\p{IsCJKUnifiedIdeographs}[^\[\]]+\[[^\[\]]+\]\.xls$' -and $_.DirectoryName -notmatch '\\备份(\\|$)' } |
|
Sort-Object FullName)
|
|
$utf8 = New-Object System.Text.UTF8Encoding($false)
|
$writer = New-Object System.IO.StreamWriter($ManifestPath, $false, $utf8)
|
$excel = $null
|
$converted = 0
|
try {
|
$excel = New-Object -ComObject Excel.Application
|
$excel.Visible = $false
|
$excel.DisplayAlerts = $false
|
$writer.WriteLine("index`tsource_path`toutput_path`tstatus")
|
for ($i = 0; $i -lt $files.Count; $i++) {
|
$file = $files[$i]
|
$dest = Join-Path $OutputRoot ('raw_{0:D4}.xlsx' -f ($i + 1))
|
$status = 'converted'
|
if (Test-Path -LiteralPath $dest) {
|
$jsonPath = Join-Path $OutputRoot ('raw_{0:D4}.json' -f ($i + 1))
|
$status = 'exists'
|
} else {
|
$workbook = $null
|
try {
|
$workbook = $excel.Workbooks.Open($file.FullName, 0, $true)
|
$workbook.SaveAs($dest, 51)
|
$converted++
|
} finally {
|
if ($null -ne $workbook) { $workbook.Close($false) }
|
}
|
$meta = [ordered]@{source_path=$file.FullName; output_path=$dest; source_size=$file.Length}
|
$metaJson = $meta | ConvertTo-Json -Compress
|
[System.IO.File]::WriteAllText((Join-Path $OutputRoot ('raw_{0:D4}.json' -f ($i + 1))), $metaJson, $utf8)
|
}
|
$writer.WriteLine(("{0}`t{1}`t{2}`t{3}" -f ($i + 1), $file.FullName, $dest, $status))
|
}
|
} finally {
|
$writer.Close()
|
if ($null -ne $excel) { $excel.Quit() }
|
[GC]::Collect()
|
[GC]::WaitForPendingFinalizers()
|
}
|
$after = @(Get-Process EXCEL -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Id)
|
$newPids = @($after | Where-Object { $_ -notin $before })
|
if ($newPids.Count -gt 0) {
|
Start-Sleep -Seconds 1
|
foreach ($pidValue in $newPids) {
|
$proc = Get-Process -Id $pidValue -ErrorAction SilentlyContinue
|
if ($null -ne $proc) { Stop-Process -Id $pidValue -Force }
|
}
|
}
|
"RAWFILES=$($files.Count) CONVERTED=$converted"
|