将多个表结果复制到Excel

时间:2016-03-02 00:52:11

标签: sql sql-server excel powershell

我有一个返回4个表的大量SQL查询。我能够返回第一个表,但这里没有其他表是我正在使用的代码。我正在使用我在网上找到的powershell脚本。我正准备通过将$DataSetTable = $DataSet.Tables[0]更改为$DataSetTable = $DataSet.Tables[1]来获取第二个表格,而第二个表格是在Excel工作表中返回的,而不是第一个表格。

我怎么能所有的桌子?

$SQLServer = 'SQLCL01'
$Database = 'home'
$SqlQuery = @' Query goes here'@

## - Connect to SQL Server using non-SMO class 'System.Data':
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection

## - Extract and build the SQL data object '$DataSetTable':
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSetTable = $DataSet.Tables[0]

## --------- Working with Excel ------- ##

## - Create an Excel Application instance:
$xlsObj = New-Object -ComObject Excel.Application

## - Create new Workbook and Sheet (Visible = 1 / 0 not visible)
$xlsObj.Visible = 1
$xlsWb = $xlsobj.Workbooks.Add()
$xlsSh = $xlsWb.Worksheets.item(1)

$xlsSh = $xlsWb.Worksheets.Item("Sheet1")
$xlsSh.Name = "Back date dump"
$xlsSh = $xlsWb.ActiveSheet

## - Build the Excel column heading:
[Array] $getColumnNames = $DataSetTable.Columns | Select ColumnName

## - Build column header:
[int] $RowHeader = 1
foreach ($ColH in $getColumnNames) {
  $xlsSh.Cells.item(1, $RowHeader).font.bold = $true
  $xlsSh.Cells.item(1, $RowHeader) = $ColH.ColumnName
  $RowHeader++
}

## - Adding the data start in row 2 column 1:
[int] $rowData = 2
[int] $colData = 1

foreach ($rec in $DataSetTable.Rows) {
  foreach ($Coln in $getColumnNames) {
    ## - Next line convert cell to be text only:
    $xlsSh.Cells.NumberFormat = "@"

    ## - Populating columns:
    $xlsSh.Cells.Item($rowData, $colData) = $rec.$($Coln.ColumnName).ToString()
    $ColData++
  }
  $rowData++; $ColData = 1
}

## - Adjusting columns in the Excel sheet:
$xlsRng = $xlsSH.usedRange
$xlsRng.EntireColumn.AutoFit()

1 个答案:

答案 0 :(得分:0)

循环集合中的所有表:

$xlsObj = New-Object -ComObject Excel.Application
foreach ($DataSetTable in $DataSet.Tables) {
  ...
}