读取写入EXCEL的单值输出

时间:2014-08-15 13:57:39

标签: sql excel powershell

我的powershell脚本运行SQL查询并将其输出到EXCEL

$SQL2 = "SELECT
    COUNT(DISTINCT EVENT_DESC) AS Number_of_Downloads,
    COUNT(DISTINCT dbo.V_SEM_COMPUTER.COMPUTER_NAME) AS Number_of_Computers
FROM
    dbo.V_AGENT_SYSTEM_LOG,  dbo.V_SEM_COMPUTER

$ws = $wb.Worksheets.Item(2)
$ws.name = "Totals"


$qt = $ws.QueryTables.Add("ODBC;DSN=$DSN;UID=$username;PWD=$password", $ws.Range("A1"), $SQL2)

if ($qt.Refresh()){
    $ws.Activate()
    $ws.Select()
    $excel.Rows.Item(1).HorizontalAlignment = $xlCenter
    $excel.Rows.Item(1).VerticalAlignment = $xlTop
    $excel.Rows.Item("1:1").Font.Name = "Calibri" 
    $excel.Rows.Item("1:1").Font.Size = 11 
    $excel.Rows.Item("1:1").Font.Bold = $true 
 }

EXCEL输出

enter image description here

如何将23884的值读入powershell变量?

现在,我查询数据库两次,“Number_of_Computers”的值在几秒钟内发生变化,因此我只需要记录一次该值。

2 个答案:

答案 0 :(得分:1)

如何使用范围A1:B1

$Range = $ws.QueryTables.Add("ODBC;DSN=$DSN;UID=$username;PWD=$password", $ws.Range("A1:B1"), $SQL2)

答案 1 :(得分:1)

获取相关单元格的.Value2属性。这应该适合你:

$NumOfComps = $ws.Cells.item(2).value2

对不起,您可以通过以下方式获得确切的单元格:

$NumOfComps = $ws.Range("B2","B2")

这只是指定一个单元格范围。