c# - Powershell脚本错误 "Cannot find an overload for "LoadFromCollection“和参数计数: "1".”

标签 c# powershell epplus

我正在尝试使用 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 的常规数组类型 - PowerShell 找不到合适的 .LoadFromCollection方法重载,导致您看到的错误。

(请注意,您的 $DemoData = New-Object System.Collections.ArrayList 语句无效:后续 $DemoData = 1..10 ... 语句将覆盖它,并分配命令返回的任何内容,即 [object[]] 数组。)

立即的解决方法是确保您使用强类型数组,这意味着:[pscustomobject[]] $DemoData = 1..10 ... ,鉴于 [pscustomobject] Select-Object 是对象的类型调用返回。

可能就足够了,具体取决于该方法使用什么反射方法来确定输入对象的属性:

  • 如果它能够通过 IDynamicMetaObjectProvider 发现属性接口(interface),其中[pscustomobject]实现,然后 [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/

相关文章:

c# - Epplus : how to display double quaotes in string concatenation formula

c# - 在负十六进制和负十进制之间转换会给出错误的结果

c# - "Use of unassigned local variable"在 if 语句中与 TryParse 一起使用动态

Powershell:使用许多文件名执行命令的更短方法?

powershell - 在Powershell中一次移动或复制多个文件

c# - 如何使用 [Display(Name ="")] 作为 LoadFromCollection 的列标题

c# - 如何从 UWP map 上的 MapIcon 中删除点和尾部

c# - 创建 Intranet 站点

powershell - Azure部署脚本不断提示 "CurrentStorageAccount is not set"

c# - EPPlus 从数据透视表创建图表