Powershell写入.XLSX会损坏文件

问题描述 投票:0回答:1

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

powershell loops xlsx xls
1个回答
0
投票

有时,使用excel处理com对象太复杂了。我建议使用import-excel模块。Install-Module -Name ImportExcel

© www.soinside.com 2019 - 2024. All rights reserved.