如何在 powershell 脚本中将整个数据从数据网格视图复制到 excel

How to copy the Whole data from Data Grid view to excel in powershell script

我正在尝试制作一个脚本来为小型初创公司创建计费 GUI。 为了根据用户输入列出产品,我创建了一个 Datagridview。我已经设法在网格中列出产品,但现在当我试图将其复制到 excel

时我感到震惊

https://github.com/RamblingCookieMonster/PSExcel 下载 PSExcel 模块,使用 Import-Module 导入它。

然后使用下面的代码:

$File = "Path to xlxs file"
$WSName = "SheetName"
$ColumnName = "E" 
$StartRowIndex = 2
$ColumnData = @("a","b","c","d")
$i = 0
$Excel = New-Excel -Path $File
$Worksheet = $Excel | Get-WorkSheet -Name $WSName
ForEach ($data in $ColumnData) {
($Worksheet.Cells | ? {$_.Address -eq "$ColumnName$($StartRowIndex +$i)"}).Value = $data
$i++
}
$Excel | Close-Excel -Save

$File 是您的 excel 文档的完整路径
$WSName 是您正在打开的 excel 文档中的工作表名称
$ColumnName 是列地址(如 excel)
$StartRowIndex 是您希望插入数据的起始行索引(从 1 开始,如 excel)
$ColumnData 是您要放入 excel 工作表中的一组值 如果您需要导出整个 datagridview table(或其中的一部分),请使用:

$File = "Path to xlxs file"
$WSName = "SheetName"
$data | Export-XLSX -Path $File -Worksheet $WSName

其中 $data 是一个 PSObject(与 Export-Csv 相同)。
如果工作表已存在于 Excel 文档中并且您需要将数据粘贴到现有工作表上,请使用 -ClearSheet 开关。