我正在尝试使用LoadfromCollection将收集对象加载到excel文件中。我正在使用EPPLUS库来这样做。但是我继续收到错误消息“找不到“LoadFromCollection”的重载,并且参数计数为“1” 。“由于我是PowerShell的新手,因此不确定如何解决该问题。另外,还有其他方法可以使用EPPLUS库加载收集对象吗?

$pkg = [OfficeOpenXml.ExcelPackage]::new($Path)
$ws  = $pkg | Add-WorkSheet -WorkSheetname 'test'

$DemoData = New-Object System.Collections.ArrayList

$DemoData = 1..10 | Foreach-Object{

        $BookID = Get-Random -Minimum 1 -Maximum 1000
        $Date = (Get-Date).adddays(-$BookID)

        New-Object -TypeName PSObject -Property @{
            Name = "Book$_"
            BookID = $BookID
            Date = $Date
        } | Select Name, BookID, Date
    }
$null = $ws.Cells['A1'].LoadFromCollection($DemoData)

最佳答案

.LoadFromCollection 是具有以下签名的通用方法:

public ExcelRangeBase LoadFromCollection<T>(
    IEnumerable<T> Collection
)
为了使PowerShell能够调用通用方法,它必须能够推断T实例的元素的具体类型IEnumerable<T>
因此,如果您的$DemoData数组不是强类型的,它是-它的类型是[object[],这是PowerShell的常规数组类型-
(请注意,您的.LoadFromCollection语句无效:后续的$DemoData = New-Object System.Collections.ArrayList语句将其覆盖,并分配命令返回的任何内容,即$DemoData = 1..10 ...数组。)
立即解决是确保您使用强类型数组,这意味着:[object[]],因为[pscustomobject[]] $DemoData = 1..10 ...[pscustomobject]调用返回的对象的类型。
这可能就足够了,这取决于该方法用于确定输入对象属性的反射方法:
  • 如果能够通过Select-Object实现的IDynamicMetaObjectProvider接口(interface)发现属性,那么[pscustomobject]类型约束就足够了。
  • 如果没有,则必须通过(PSv5 +)自定义类创建常规.NET类型,如下所示:
  • # PowerShell v5 and above.
    
    $pkg = [OfficeOpenXml.ExcelPackage]::new($Path)
    $ws  = $pkg | Add-WorkSheet -WorkSheetname 'test'
    
    # Define a custom class with the properties of interest.
    class Custom {
      [string]   $Name
      [int]      $BookID
      [datetime] $Date
    }
    
    [Custom[]] $DemoData = 1..10 | Foreach-Object{
    
      $BookID = Get-Random -Minimum 1 -Maximum 1000
      $Date = (Get-Date).adddays(-$BookID)
    
      # Create and output a [Custom] instance with the specified property values.
      [Custom] @{ Name = "Book$_"; BookId = $BookID; Date = $Date }
    
    }
    
    # Call .LoadFromCollection with the strongly typed array.
    $null = $ws.Cells['A1'].LoadFromCollection($DemoData)
    

    关于c# - Powershell脚本错误 “Cannot find an overload for ” LoadFromCollection”和参数计数:1“.”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62638768/

    10-09 01:06