【发布时间】:2021-03-30 08:03:09
【问题描述】:
我开发了一个脚本,它从 SQL 服务器获取数据,并以这种方式使用 ImportExcel 模块将其放入 Excel 工作表中:
# *** Data Retrieve ***
$dt1 = SQLCommand -File_Path $QueryReplacedFullPath -Server "Server1" -Name "Database1" -User "user1" -Password $pass -Out
$dt_table1 = $dt1.Tables[0]
# *** Excel Preparation ***
if ($dt_table1.Rows.Count -eq 0)
{
$params = @{
Path = $DestinationExcelFilePath
WorksheetName = $SheetName
HideSheet = $SheetName
}
Export-Excel @params
}
else
{
$exportToExcel = ForEach ($Row in $dt1.Tables[0].Rows)
{
$properties = @{}
ForEach ($Col in $dt1.Tables[0].Columns.ColumnName)
{
$properties[$Col] = $Row.$Col
}
[PSCustomObject]$properties
}
$params = @{
Path = $DestinationExcelFilePath
WorksheetName = "1"
TableName = 'Table1'
FreezeTopRow = $true
Calculate = $true
}
$exportToExcel | Export-Excel @params
}
#*** Excel Refresh ***
$Excel = New-Object -ComObject Excel.Application
$Excel.DisplayAlerts = $false
$Excel.Visible = $False
$Workbook = $Excel.Workbooks.Open($DestinationExcelFilePath,$null,$false)
$Workbook.RefreshAll()
$WorkSheet = $Workbook.worksheets | where-object {$_.Name -eq $MainSheetName}
$WorkSheet.Activate()
[void]$Workbook.Save()
[void]$Workbook.Close()
[void]$Excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) | Out-Null
kill -processname excel
我正在尝试使用 Powershell 在 Excel 中做一些报告。
现在,我有一个 Excel 模板,其中包含一些带有我客户徽标的自定义图表和一个名为“Main”的工作表中的一些自定义数据透视表。 “主要”工作表中的数据透视表和图表由工作表中名为“1”的表格中的数据提供,之前用我的脚本填充。
但是,尝试 RefreshAll() 工作簿时执行失败。据我所知,我的脚本“创建”了一个新工作表“1”,而不是在我的模板中填充现有工作表,这导致图表进入“混乱”状态,因为它试图更新数据。当我打开 Excel 文件时,我看到 Excel 询问我是否要刷新 char 数据,因为数据已更改,如果我单击“是”,我看到所有更新。
我想知道如何避免这种情况,我想在不为我的工作簿中的每个图表按“是”的情况下生成报告,有没有办法使用这个模块来做到这一点?或者可能是一个脚本来打开工作簿并为出现的每个弹出窗口自动单击“是”。
【问题讨论】:
标签: excel powershell script