首先让我感谢那些回答我之前问题的人。你们真棒!
这是我的问题: 我喜欢查询我的sql server存储过程并返回一个datareader。但是我想从中创建一个表。我将使用该表来使用新的Powershell OpenXML命令行开关加载excel。当我尝试构建DataTable时代码失败。我认为我没有正确地使用新对象“System.Object []”。这是我到目前为止所得到的:
$sqlConnection = new-object System.Data.SqlClient.SqlConnection "server=localhost;database=Demo;Integrated Security=sspi"
$sqlConnection.Open()
#Create a command object
$sqlCommand = $sqlConnection.CreateCommand()
$sqlCommand.CommandText = "EXEC Demo.usp_GetTableValueParameter_Data"
#Execute the Command
$sqlReader = $sqlCommand.ExecuteReader()
#Parse the records
$sqlReader | &{ begin{$values = new-object "System.Object[]" $sqlReader["Name"], $sqlReader["Level_Desc"], $sqlReader["Level"]} process {$_.GetValues($values); $datatable.Rows.Add($values)}}
##$datatable | format-table -autosize
# Close the database connection
$sqlConnection.Close()
#STARTING OPENXML PROCESS
#----------------------------
$xlsFile = "C:\Temp\Data.xlsx"
$datatable | Export-OpenXmlSpreadSheet -OutputPath $xlsFile -InitialRow 3
答案 0 :(得分:15)
将Mladen's answer翻译成PowerShell非常简单:
$sqlConnection = new-object System.Data.SqlClient.SqlConnection "server=localhost;database=Demo;Integrated Security=sspi"
$sqlConnection.Open()
#Create a command object
$sqlCommand = $sqlConnection.CreateCommand()
$sqlCommand.CommandText = "EXEC Demo.usp_GetTableValueParameter_Data"
#Execute the Command
$sqlReader = $sqlCommand.ExecuteReader()
$Datatable = New-Object System.Data.DataTable
$DataTable.Load($SqlReader)
# Close the database connection
$sqlConnection.Close()
#STARTING OPENXML PROCESS
#----------------------------
$xlsFile = "C:\Temp\Data.xlsx"
$datatable | Export-OpenXmlSpreadSheet -OutputPath $xlsFile -InitialRow 3
但是,如果你只需要一个DataTable,你不需要在命令上调用ExecuteReader,你可以创建一个DataAdapter并使用它来填充DataTable:
$sqlConnection = new-object System.Data.SqlClient.SqlConnection "server=localhost;database=Demo;Integrated Security=sspi"
$sqlConnection.Open()
#Create a command object
$sqlCommand = $sqlConnection.CreateCommand()
$sqlCommand.CommandText = "EXEC Demo.usp_GetTableValueParameter_Data"
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter $sqlcommand
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | out-null
# Close the database connection
$sqlConnection.Close()
$datatable = $dataset.Tables[0]
#STARTING OPENXML PROCESS
#----------------------------
$xlsFile = "C:\Temp\Data.xlsx"
$datatable | Export-OpenXmlSpreadSheet -OutputPath $xlsFile -InitialRow 3
答案 1 :(得分:3)
我不知道如何在powershell中执行此操作,但在.net中,您可以这样做:
DataTable dt = new DataTable();
dt.Load(yourSqlReader);