【发布时间】:2020-01-13 19:14:05
【问题描述】:
我有一个 Powershell 脚本,它循环遍历文件夹中的 .xslx 文件,密码用文件名保护它们(目前)。循环和写入 .xls 没有问题,但是当我尝试打开 .使用 Powershell 编写后的 xlsx 文件 - 我收到错误:
Excel 无法打开文件“abcd.xlsx”,因为文件格式或文件 扩展无效。验证文件没有损坏 并且文件扩展名与文件格式匹配。
这是脚本:
function Release-Ref ($ref) {
([System.Runtime.InteropServices.Marshal]::ReleaseComObject(
[System.__ComObject]$ref) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
$e = $ErrorActionPreference
$ErrorActionPreference="continue"
foreach ($f in Get-ChildItem "C:"){
try{
$ff = $f
$xlNormal = -4143
$s = [System.IO.Path]::GetFileNameWithoutExtension($f)
$xl = new-object -comobject excel.application
$xl.Visible = $False
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open($ff.FullName)
$wb.sheets(1).columns("A:S").entirecolumn.AutoFit()
$wb.sheets(1).columns("N").NumberFormat = "0.0%"
$a = $wb.SaveAs("C:\Out\" + $s + ".xls",$xlNormal,$s) #works
#$a = $wb.SaveAs("C:\Out\" + $s + ".xlsx",$xlNormal,$s) #doesn't work
$a = $xl.Quit()
$a = Release-Ref($ws)
$a = Release-Ref($wb)
$a = Release-Ref($xl)
}
catch {
Write-Output "Exception"
$ErrorActionPreference=$e;
}
}
我搜索了其他问题,但找不到从 Powershell 编写的相同问题的任何其他示例。谢谢。
【问题讨论】:
-
xls != xlsx。前者是二进制格式,后者是包含 XML 的 zip。尝试另存为 xlsx,但使用 file format value 51。
-
我没有考虑过这部分 - 非常感谢您的观点和解释。就是这样 - 如果您想添加答案,我会接受,谢谢!
标签: powershell loops xlsx xls