我需要使用PowerShell将大量数据导出到Excel。
首先,我使用了这个很棒的模块https://github.com/dfinke/ImportExcel但它的工作速度很慢。
它逐个单元地用EPPlus.dll写入数据,所以它很慢。
dll还有一些方法可以同时加载一个对象数组或一个DataTable,速度要快得多,我可以让DataTable方法工作但是我无法弄清楚如何使用&#34加载数组; LoadFromArrays"
示例:
# Install and Load
Install-Package EPPlus -Scope CurrentUser -provider Nuget -Source https://www.nuget.org/api/v2
Add-Type -path "$env:LOCALAPPDATA\PackageManagement\NuGet\Packages\EPPlus.4.1.1\lib\net40\EPPlus.dll"
# Initialize Data
$Path = 'C:\Temp\Test.xlsx'
$pkg = [OfficeOpenXml.ExcelPackage]::new($Path)
$ws = $pkg | Add-WorkSheet -WorkSheetname 'test'
# Single Cell Works
$ws.Cells['A1'].Value = 8
# DataTable Works
$myDataTable = New-Object System.Data.DataTable
$null = $myDataTable.Columns.Add( 'Column1' )
$null = $myDataTable.Columns.Add( 'Column2' )
$null = $myDataTable.Columns.Add( 'Column3' )
$null = $myDataTable.Rows.Add( 'value1','value2','value3' )
$null = $myDataTable.Rows.Add( 'valueA','valueB','valueC' )
$null = $myDataTable.Rows.Add( 'valueD','value2','valueE' )
$null = $ws.Cells['A1'].LoadFromDataTable($myDataTable,$true)
# How to Load an Arrays?
$Process = Get-Process
$null = $ws.Cells['A1'].LoadFromArrays($Process)
$Process = @([PSCustomObject]@{A = 1},[PSCustomObject]@{A = 2})
$null = $ws.Cells['A1'].LoadFromArrays($Process)
# I get the Error:
#[2,1] Cannot convert argument "Data", with value: "System.Object[]", for "LoadFromArrays" to type "System.Collections.Generic.IEnumerable`1[System.Object[]]": "Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Collections.Generic.IEnumerable`1[System.Object[]]"."
# Save to disk
$pkg.Save()
$pkg.Dispose()
谢谢