【问题标题】:Powershell: Excel combine worksheets into a single worksheetPowershell:Excel 将工作表组合成一个工作表
【发布时间】:2015-03-22 00:19:58
【问题描述】:

我有一些 Web 脚本,我已经对其进行了调整,可以运行 7 个 T-SQL 查询并将结果输出到 1 个 Excel 工作簿中,每个查询一个工作表。刚刚有人问我是否可以将所有 7 个工作表合二为一。

这是我复制工作表的示例代码,但是选择了整个列而不是只选择了 UsedData。此外,目标工作表上第一个工作表的数据将替换为第二个工作表数据。

问题:让 Powershell 将 7 个查询输出到一个由两个空白行分隔的 Excel 工作表中会更简单吗?或者修改现有的 Powershell 脚本来创建 7 个工作表,然后将它们合二为一?

代码不漂亮!我也一直迷失在使用$Excel = New-Object -ComObject excel.application$Excel | Get-Member 来探索如何让 PowerShell 与 Excel 一起工作。 MSDN 上的参考资料通常是针对 VB 或 C 语言的,我无法将其翻译成 PowerShell。

--编辑,添加将7个Query结果存储在一个数组中并输出到控制台的代码。数据是正确的,但我只是不确定如何将这些数据通过管道传输到单个 Excel 工作表中。

$docs = "C:\Temp\SQL\test.xlsx"
If (Test-Path $docs){Remove-Item $docs}
Function First-Query {
param([string[]]$queries)
$xlsObj = New-Object -ComObject Excel.Application
$xlsObj.DisplayAlerts = $false
## - Create new Workbook and Sheet (Visible = 1 / 0 not visible)
$xlsObj.Visible = 0
$xlsWb = $xlsobj.Workbooks.Add(1)
$xlsSh = $xlsWb.Worksheets.Add([System.Reflection.Missing]::Value, $xlsWb.Worksheets.Item($xlsWb.Worksheets.Coun))
$xlsSh.Name = 'Test'
for ($i = 0; $i -lt $queries.Count; $i++){
$query = $queries[$i]
$SQLServer = 'Server'
$Database = 'DataBase'
## - 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 = $query
$SqlCmd.Connection = $SqlConnection
## - Extract and build the SQL data object '$DataSetTable':
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd;
$tables = New-Object System.Data.DataSet;
$SqlAdapter.Fill($tables)
$TableArray = @($tables)
$SqlConnection.Close()
$DataSetTable = $TableArray.Tables[0]
}#End For Loop
## - 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() | Out-Null
#End for loop.
#Delete unwanted Sheet1.
$xlsWb.Sheets.Item('Sheet1').Delete()
#Set Monday to Active Sheet upon opening Workbook.
$xlsWb.Sheets.Item('Monday').Activate()
## ---------- Saving file and Terminating Excel Application ---------- ##
$xlsFile = "C:\Temp\SQL\test.xlsx"
$xlsObj.ActiveWorkbook.SaveAs($xlsFile) | Out-Null
$xlsObj.Quit()
## - End of Script - ##
start-sleep 2
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsRng)) {'cleanup xlsRng'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsSh)) {'cleanup xlsSh'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsWb)) {'cleanup xlsWb'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsObj)) {'cleanup xlsObj'}
[gc]::collect() | Out-Null
[gc]::WaitForPendingFinalizers() | Out-Null
}#End Function
$queries = @()
$queries += @'
SELECT DISTINCT
'@
First-Query -queries $queries

【问题讨论】:

  • 就我个人而言,我宁愿在 powershell 中操作数据并将其粘贴到 Excel 中,而不是在 Excel 中尝试操作数据
  • 我敢打赌将查询结果存储在一个数组中会是理想的,因为唯一的要求是查询结果之间有两个空白行。
  • 我让脚本正常工作,运行 7 个查询,但最后一个查询是插入到 excel 工作簿中的唯一数据。
  • 您应该发布一个答案,并将其标记为已接受,以便解决此问题,并且未来的用户可以从您的进步中受益

标签: arrays excel powershell


【解决方案1】:

不确定我是否真的理解您的问题,但下面是一个“模板”,可以帮助您做您想做的事。它向您展示了如何创建工作表和处理它们。您必须填写空白(请参阅注释部分,您必须在其中调用查询函数)。

param (
    [string] $ExcelFile = (Read-Host "Enter full path for Excel file")
)

try
{
    $Error.Clear()

    # http://support.microsoft.com/kb/320369
    [System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo] "en-US"

    Push-Location
    $scriptPath = Split-Path -parent $MyInvocation.MyCommand.Path

    Set-Location $scriptPath

    $Excel = New-Object -comobject Excel.Application
    $Excel.Visible = $True

    $WorksheetCount = 7

    $Workbook = $Excel.Workbooks.Add()
    $Workbook.Title = 'My Workbook'


    $weekdays = @("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")


    ($WorksheetCount - 1)..0 | %{

        $sheet = $Excel.Worksheets.Add()
        $sheet.Name = $weekdays[$_]

        # $dataTable = Execute-Your-Query-Here-Returning-A-Data-Table

        # $x = 0
        # $dataTable | %{
            # $sheet.cells.item($x, 1) =  ...
            # $sheet.cells.item($x, 2) =  ...
            # $x++
        # }
    }   

    $excel.ActiveWorkbook.SaveAs("$ExcelFile")
 }

catch
{
    "$($MyInvocation.InvocationName): $Error"
}

finally
{
    Pop-Location

    $Excel.Quit()
    $Excel = $null

    [gc]::collect()
    [gc]::WaitForPendingFinalizers()
}

【讨论】:

    猜你喜欢
    • 2019-07-26
    • 1970-01-01
    • 2022-12-24
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    相关资源
    最近更新 更多