首页 > 解决方案 > Powershell 写入 .XLSX 会损坏文件

问题描述

我有一个 Powershell 脚本,它循环遍历文件夹中的 .xslx 文件,密码用文件名保护它们(现在)。循环和写入 .xls 没有问题,但是当我尝试打开 .xlsx 文件后用 Powershell 编写它 - 我收到错误:

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 编写的相同问题的任何其他示例。谢谢你。

标签: powershellloopsxlsxxls

解决方案


使用 excel 有时使用 com 对象太复杂了。我推荐这个import-excel模块。 Install-Module -Name ImportExcel

然后你可以做这样的事情。

function Release-Ref ($ref) { 
    $e = $ErrorActionPreference
    $ErrorActionPreference="continue"

foreach ($f in Get-ChildItem $file){
    try{
        $filePass = gci $f
        $path = split-path $f
        $newFile = $path + "\" + $f.BaseName + "-protected.xlsx"
        $f | Export-excel $newFile -password $filePass -NoNumberConversion * -AutoSize
    }
    catch {
        Write-Output "Exception"
        $ErrorActionPreference=$e;
    }
}
}

推荐阅读