以下代码在 Powershell V1 (Excel 2007) 中引发异常:
$E = New-Object -COM "Excel.Application"
$E.Visible = $True
$wb = $E.Workbooks.Add() #<<<Exception here
该错误表示格式可能是旧的或类型库无效(从西班牙语翻译)。Word 的类似脚本工作得很好。
以下代码在 Powershell V1 (Excel 2007) 中引发异常:
$E = New-Object -COM "Excel.Application"
$E.Visible = $True
$wb = $E.Workbooks.Add() #<<<Exception here
该错误表示格式可能是旧的或类型库无效(从西班牙语翻译)。Word 的类似脚本工作得很好。
当当前文化不是 en-US 时,Office 互操作程序集似乎存在此问题。显而易见的解决方法是设置文化。
在交互式控制台上将整个操作作为单个命令运行非常重要,因为 PowerShell V1 总是为每个命令调用创建一个新线程。
PS C:\Users\jachymko> $e = new-object -com excel.application
PS C:\Users\jachymko> $e.workbooks.add()
Exception calling "Add" with "0" argument(s): "Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))"
At line:1 char:17
+ $e.workbooks.add <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
PS C:\Users\jachymko> & {
>> [threading.thread]::CurrentThread.CurrentCulture = 'en-US'
>> $e = new-object -com excel.application
>> $e.workbooks.add()
>> $e.visible=1
>> }
>>
改编自MS 帮助和支持文章 320369中提出的解决方案之一的 Powershell 。
$ci = new-object system.globalization.cultureinfo "en-US"
$e = New-Object -COM "Excel.Application"
$e.Visible = $True
$e.UserControl= $True
$books = $e.Workbooks
$books.PSBase.GetType().InvokeMember( `
"Add", `
[system.reflection.bindingflags]::InvokeMethod, `
$null, $books, $null, $ci)
来自同一篇文章:
当您对区域设置与 Office 的当前语言版本不匹配的计算机使用这些解决方法之一时,您应该熟悉 Excel 的行为方式以及 Excel 如何解释可能针对特定区域设置格式化的数据。
我在尝试打开工作簿时遇到了这个问题。我添加了这一行:
[threading.thread]::CurrentThread.CurrentCulture = 'en-US'