2017-05-26 61 views
2

我想使用EPPlus根据属性值查找范围内的所有单元格。假设我需要在现有的电子表格中查找所有含粗体文本的单元格。我需要创建将接受一个可配置的性能参数的功能,但我使用存储在一个变量属性有问题:Powershell:存储在变量中的属性

$cellobject = $ws.cells[1,1,10,10] 
$properties = 'Style.Font.Bold' 

$cellobject.$properties 
$cellobject.{$properties} 
$cellobject.($properties) 
$cellobject."$properties" 

这些工作都没有,并导致调用深度溢出。

如果这种方式不行,我可以使用库中的东西吗?

编辑:为了证明我更新与HanShotFirst提供概念的功能,最终的解决方案......

function Get-CellObject($ExcelSheet,[string]$PropertyString,[regex]$Value){ 

    #First you have to get the last row with text, 
    #solution for that is not provided here... 
    $Row = Get-LastUsedRow -ExcelSheet $ExcelSheet -Dimension $true 

    while($Row -gt 0){ 
     $range = $ExcelSheet.Cells[$Row, 1, $Row, $ExcelSheet.Dimension.End.Column] 

     foreach($cellObject in $range){ 

      if($PropertyString -like '*.*'){ 
       $PropertyArr = $PropertyString.Split('.') 
       $thisObject = $cellObject 

       foreach($Property in $PropertyArr){ 
        $thisObject = $thisObject.$Property 

        if($thisObject -match $Value){ 
         $cellObject 
        } 
       } 
      } 
      else{ 
       if($cellObject.$PropertyString -match $Value){ 
        $cellObject 
       } 
      } 
     } 
     $Row-- 
    } 
} 
#The ExcelSheet parameter takes a worksheet object 
Get-CellObject -ExcelSheet $ws -Property 'Style.Font.Bold' -Value 'True' 
+0

你尝试'$ cellobject.properties'? – Moerwald

+0

@Moerwald先生,我试过了。但重点是保持属性在函数中可配置,所以这就是为什么我需要将属性存储在变量中。那有意义吗? – Mack

+0

问题似乎是字符串$ properties中的句点。 – Mack

回答

3

点走进性能并没有真正用字符串工作。您需要分离属性的图层。以下是三层属性的对象示例。

# create object 
$props = @{ 
    first = @{ 
     second = @{ 
      third = 'test' 
     } 
    } 
} 
$obj = New-Object -TypeName psobject -Property $props 

# outputs "test" 
$obj.first.second.third 

# does not work 
$obj.'first.second.third' 

# outputs "test" 
$a = 'first' 
$b = 'second' 
$c = 'third' 
$obj.$a.$b.$c 

在您的例子,这将是这样的:

$cellobject = $ws.cells[1,1,10,10] 
$p1 = 'Style' 
$p2 = 'Font' 
$p3 = 'Bold' 

$cellobject.$p1.$p2.$p3 

或者你也可以做到这一点有点动态。这应该产生相同的结果:

$cellobject = $ws.cells[1,1,10,10]  
$props = 'Style.Font.Bold'.Split('.') 
$result = $cellobject 
foreach ($prop in $props) { 
    $result = $result.$prop 
} 
$result 

而且,由于上周五,这里是它的一个功能:)

function GetValue { 
    param (
     [psobject]$InputObject, 
     [string]$PropertyString 
    ) 

    if ($PropertyString -like '*.*') { 
     $props = $PropertyString.Split('.') 
     $result = $InputObject 
     foreach ($prop in $props) { 
      $result = $result.$prop 
     } 
    } else { 
     $result = $InputObject.$PropertyString 
    } 

    $result 
} 

# then call the function 
GetValue -InputObject $cellobject -PropertyString 'Style.Font.Bold' 
+0

感谢您的回复。你会提供一个功能的例子吗?问题在于'$ cellobject'中的单元格编号是在循环中自动计算的,我需要添加这些属性作为参数并返回正确的对象。这是有道理的? 所以你说没有办法加入所有三个属性作为一个通过,是吗? – Mack

+0

哎呀,我刚刚看到你编辑了答案。 – Mack

+0

增加了另一个具有函数的例子。 – HanShotFirst