我尝试在PowerShell中执行SQL查询,该查询将拉出转储并在Excel中输入输出数据。以下是我使用的PS代码,它只填充Excel中的几个单元格,无法填充包含数据类型为Float,Double,Int32等的单元格。
$servers = "VINESH-PC"
$query =
@'
SELECT top 100 * FROM PROFILE_DUMP
'@
$Filename='SQL_DUMP'
# Open Excel
$xl = new-object -comobject excel.application
$xl = $xl.Workbooks.Add()
$ExcelWorkSheet = $xl.Worksheets.Add()
$xl.Visible = $true
$rowCount = 2
foreach ($s in $servers)
{
$results = invoke-sqlcmd -ServerInstance $s -Query $query
foreach ($r in $results)
{
# set up col and server info
$ColCount = 1
for ($i=1; $i -le $r.ItemArray.Count; $i ++)
{
$ExcelWorkSheet.Cells.Item($rowCount,$ColCount).Numberformat='@'
$ExcelWorkSheet.Cells.Item($rowCount,$ColCount).Value2 = $r.ItemArray[$i-1]
$ColCount ++
}
$rowCount ++
}
}
# Add Header to Sheet
$headers = $results | Get-Member -Membertype property
$h = 1
foreach ($header in $headers)
{
$ExcelWorkSheet.Cells.Item(1,$h).Value2 = $header.name
$h ++
}
## Format Excel Spreadsheet
$listObject = $ExcelWorkSheet.ListObjects.Add([Microsoft.Office.Interop.Excel.XlListObjectSourceType]::xlSrcRange, $ExcelWorkSheet.UsedRange, $null,[Microsoft.Office.Interop.Excel.XlYesNoGuess]::xlYes,$null)
$listObject.Name = "User Table"
$listObject.TableStyle = "TableStyleLight9"
## auto size cols
$ExcelWorkSheet.UsedRange.Columns.Autofit() | Out-Null
##Save and exit the excel file
$filePathSave="E:\PowerShell_Dev\SQL_DUMP_PULLER\$Filename.xlsx"
$xl.SaveAs($filePathSave)
$xl.Close()
$xl.Quit()
收到以下错误。
- 无法投射“System.Double”类型的对象。输入' System.String'。
- 无法转换类型为#System ;DBNull'的对象输入' System.String'。
- 无法投射“System.Int32'”类型的对象输入' System.String'。
我是否需要附加任何代码来解决此错误?