查找MS Office Interop常量的值而不是硬编码

时间:2010-11-24 23:03:19

标签: com powershell ms-office office-interop

使用PowerShell,可以轻松创建Excel Application类的实例并开始操作它:

$app = New-Object -ComObject "Excel.Application"

但是,如果我需要使用像xlDoubleQuote或xlDelimited这样的常量 - 似乎我不得不对它们进行硬编码。我真的希望能够做到这样的事情:

$constants = New-Object -ComObject "Excel.Constants"
$constants.xlDoubleQuote

并且看到它将返回值1.不幸的是我无法创建枚举的实例,并且似乎没有像普通.NET类库那样引用它的方法:< / p>

[Excel.Constants]::xlDoubleQuote

有没有办法将该枚举动态导入PowerShell?也许通过托管库而不是COM?

5 个答案:

答案 0 :(得分:9)

使用Excel的主互操作程序集。如果您安装了Office,则这些应该在GAC中。像这样使用:

Add-Type -AssemblyName Microsoft.Office.Interop.Excel
[int][Microsoft.Office.Interop.Excel.Constants]::xlDoubleQuote

答案 1 :(得分:4)

基思已经给你答案,这是另一个选择。您可以在$ xlConstants对象上使用制表符完成来获取常量:

$xl = New-Object -ComObject Excel.Application
$constants = $xl.gettype().assembly.getexportedtypes() | where-object {$_.IsEnum -and $_.name -eq 'constants'}

$pso = new-object psobject
[enum]::getNames($constants) | foreach { $pso | Add-Member -MemberType NoteProperty $_ ($constants::$_) }
$xlConstants = $pso

答案 2 :(得分:1)

然而,基思和谢伊给出了完美的答案,请注意:

使用Excel 2003或Excel 2007时,应在计算机上安装Office主互操作程序集(PIA)。 Microsoft提供了可再发行版本。有关详细信息,请参阅此stackoverflow.com发布此处:

Different Interop references on two different computers doesn't work

答案 3 :(得分:0)

使用32位Visio 2016,我发现尝试使用Keith Hill的方法会导致错误消息:“添加类型:无法添加类型。找不到程序集'Microsoft.Office.Interop.Visio'。” Shay Levy的方法需要更多修改才能与Visio一起使用。这就是我能够开始工作的地方:

$visioApp = New-Object -ComObject Visio.Application 
$visioConstants = @{}

$visioEnums = $visioApp.gettype().assembly.getexportedtypes() | where-object {$_.IsEnum } #-and $_.name -eq 'constants'}

The answers of Keith Hill and Shay Levy are best, however, I found that Visio 
$visioEnums |%{
    $enumname = $_
    [enum]::getNames($enumname) | foreach {
        $val = invoke-expression "[$($enumname)]::$($_).value__"
        $visConstants.$_ = $val
    }
}
$visioApp.Quit()

echo $visConstants.visTopEdge 

令人失望的是,我测试时大约需要12秒钟才能执行。

答案 4 :(得分:0)

要将Keith Hill's helpful answer中的技术与Shay Levy's answer中的制表符完成想法结合起来:

# Instantiate Excel, which implicitly loads the interop
# assembly that contains the [enum] type of interest.
# Assign to $null, if you're not planning on using the object further.
$xl = New-Object -ComObject Excel.Application

# Store the [enum] type of interest in a variable for easier access.
$xlConstants = [Microsoft.Office.Interop.Excel.Constants]

注意:要查找Constants类型的全名,可以使用制表符补全:运行New-Object -ComObject Excel.Application后,键入[constants<tab>(不要键入结尾{{1 }}),应扩展为];如果显示的是来自{<1> other 以外的名称空间的[Microsoft.Office.Interop.Excel.Constants类型,请按Tab键,直到找到所需的类型。

现在您可以:

  • 通过Microsoft.Office.Interop.Excel运算符访问单个枚举值作为$xlConstants中存储的类型的静态成员,该运算符也可用于制表符补全;例如:

    ::
  • 通过强制转换为$xlConstants::xl3d<tab> # -> expands to $xlConstants::xl3DBar 或访问[int]属性来获取特定值的基础数字:

    .Value__
  • 枚举所有符号名称:

    [int] $xlConstants::xl3DBar    # -> -4099
    
    $xlConstants::xl3DBar.Value__  # ditto
    
  • 还要显示符号名称下面的数字:

    [enum]::GetNames($xlConstants)
    
相关问题