Powershell中的Excel workbooks.saveas()错误 [英] Excel workbooks.saveas() error in powershell

查看:109
本文介绍了Powershell中的Excel workbooks.saveas()错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将.xls文件转换为.xlxs
我尝试了此代码的许多变体,但每次遇到此错误消息时:

I'm trying to convert .xls files to .xlxs I tried many variations of this code but every time i'm facing this error message :

另存为异常avec«2»自变量:«
类保存工作簿,但仍为échoué。 »Aucaractère
C:\temp\xlsx.ps1:18:6

Exception lors de l'appel de « SaveAs » avec « 2 » argument(s) : « La méthode SaveAs de la classe Workbook a échoué. » Au caractère C:\temp\xlsx.ps1:18 : 6


  • try {$ opendoc.saveas( $ basename,$ saveFormat)}

  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~


    • CategoryInfo:未指定:(:) [],MethodInvocationException

    • FullyQualifiedErrorId:ComMethodTargetInvocation

    这是我的代码:

    $excel = new-object -comobject excel.application
    $excel.Visible = $false
    $saveFormat = "xlOpenXMLWorkbook";
    
    ls c:\temp\*.xls | %{
        $opendoc = $excel.workbooks.open($_.FullName)
        $excel.DisplayAlerts =$false 
        $basename = $_.basename
        try{
            $opendoc.saveas($basename,$saveFormat,$null,$null,$false,$false,"xlNoChange","xlLocalSessionChanges")
          # tried this one and got same error : $opendoc.saveas($basename, $saveFormat)}
        }
        catch{
            $opendoc.close();$excel.quit()
            $_ 
        }
        $opendoc.close();   
    }
    
    $excel.quit()    
    

    请知道工作方法吗?

    推荐答案

    将常量传递到 SaveAs 方法通常表示数字值,而不是字符串。在您的情况下,第二个参数可能应该是51( xlWorkbookDefault ),如在此处 。其他两个字符串( xlNoChange 也是如此,其中应该为1 ,并且 xlLocalSessionChanges ,其中应该为2 )。您需要使用数字值,也可以自己定义常量,例如:

    Constants passed into the SaveAs method usually represent numeric values, not strings. In your case the second parameter probably should be 51 (xlWorkbookDefault) as documented here. Same goes for the other two strings ("xlNoChange", which should be 1, and "xlLocalSessionChanges", which should be 2). You need to either use the numeric values, or define the constants yourself, e.g.:

    $xlWorkbookDefault     = 51
    $xlNoChange            =  1
    $xlLocalSessionChanges =  2
    

    此外,您不能使用 $ null 用于应保留默认值的参数。使用 [Type] :: Missing

    Also, you cannot use $null for arguments that should retain default values. Use [Type]::Missing instead.

    更改此:

    $opendoc.saveas($basename,$saveFormat,$null,$null,$false,$false,"xlNoChange","xlLocalSessionChanges")
    

    $opendoc.SaveAs($basename, 51, [Type]::Missing, [Type]::Missing, $false, $false, 1, 2)
    

    这篇关于Powershell中的Excel workbooks.saveas()错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆