将SQL输出导出到Excel工作表

我想输出到Excel文件,我给一个名称,即不是“Sheet1”的表输出。 我怎么开始这个代码呢?

下面是当前读取sql输出的代码

$sql_output = @() while ($rdr.read()){ $sql_output += [PSCustomObject][Ordered]@{ Col1=$rdr.GetValue(0) Col2=$rdr.GetValue(1) Col3=$rdr.GetValue(2) Col4=$rdr.GetValue(3) Col5=$rdr.GetValue(4) } $count=$count + 1 } 

然后导出到csv

 $sql_output | Export-CSV "D:\Script\Network_Threat_Protection.csv" -NoTypeInfo -Append 

我最终会喜欢这个PowerShell脚本读取多个SQL查询,并将其输出到Excel中的不同工作表,但让我得到杰出的出口到Excel首先….

Export-CSV不会生成Excel文件。 它生成一个逗号分隔的文本文件,通常设置为使用Excel 打开 。 作为一个CSV文件,并不知道像sheetnames这样的多个工作表或数据集属性,因为您需要使用Excel comobject(及其所有的细微差别)。

下面是编写一个真正的 Excel文件的基本示例:

 $a = New-Object -com Excel.Application $a.Visible = $True $b = $a.Workbooks.Add() $c = $b.Worksheets.Item(1) $c.Cells.Item(1,1) = "A value in cell A1." $b.SaveAs("C:\Scripts\Test.xls") $a.Quit() 

你试图做的不是新的。 在这个任务上有很多脚本在互联网上。 微软的脚本中心是findPowerShell脚本的好地方。 这是一个似乎做你想要的东西。