2015-12-02 59 views
2

我想通過使用嵌套for循環,將在Excel中打開一個乘法表10x10。到目前爲止,我有這個打開的Excel:乘法表Powershell

$excel = New-Object -COMObject Excel.Application 
$excel.Visible = $true 
$excel.Workbooks.Add() 

這顯示錶:

for ($i = 1; $i -le 10; $i++) { 
    for ($j = 1; $j -lt 10; $j++) { 
     $total = $i * $j; 
     Write-output $total 
    } 
} 

但該表沒有在10×10格式表,但一個接一個下顯示。有人可以幫我把它放在一起,或給我一些提示如何使它工作?

回答

0
  • 你2個for迴路應具有相同的退出條件(-le 10)

  • 每次使用Write-Output時間寫入一個新行到控制檯。

  • 你只需要第一線Excel所需要的,你需要更多的 :)。

如果你想輸出的表,你可以做這樣說控制檯:

#for each row 
for ($i = 1; $i -le 10; $i++) { 
    #declare an array to hold the row values 
    $row = @() 
    #for each column 
    for ($j = 1; $j -le 10; $j++) { 
     #add value to array 
     $row += $i * $j 
    } 
    #output the array, joining cells with tabs (`t) 
    $row -join "`t" 
} 

輸出:

1 2 3 4 5 6 7 8 9 10 
2 4 6 8 10 12 14 16 18 20 
3 6 9 12 15 18 21 24 27 30 
4 8 12 16 20 24 28 32 36 40 
5 10 15 20 25 30 35 40 45 50 
6 12 18 24 30 36 42 48 54 60 
7 14 21 28 35 42 49 56 63 70 
8 16 24 32 40 48 56 64 72 80 
9 18 27 36 45 54 63 72 81 90 
10 20 30 40 50 60 70 80 90 100 

現在,如果你要輸出這個到Excel ,你可以這樣做:

#create Excel Application object 
$excel = New-Object -ComObject Excel.Application 

#make Excel window visible 
$excel.Visible = $true 

#create a new workbook 
$book = $excel.Workbooks.Add() 

#select the first sheet 
$sheet = $book.Worksheets.Item(1) 

#name it as you like 
$sheet.Name = "Multiply" 

#build the header row (bold) 
for ($j = 1; $j -le 10; $j++) { 
    $sheet.Cells.Item(1, $j + 1).Value2 = $j 
    $sheet.Cells.Item(1, $j + 1).Font.Bold = $true 
} 

#build the other rows 
for ($i = 1; $i -le 10; $i++) { 

    #"header" cell (bold) 
    $sheet.Cells.Item($i + 1, 1).Value2 = $i 
    $sheet.Cells.Item($i + 1, 1).Font.Bold = $true 

    #other cells 
    for ($j = 1; $j -le 10; $j++) { 
     $sheet.Cells.Item($i + 1, $j + 1).Value2 = $i * $j 
    } 
} 

試試這並告訴我你是否需要調整。我會評論這些代碼,以便更好地理解。

+0

謝謝你的解釋。我唯一的問題是標題行不顯示所有的數字。標題行的單元格B1中只有數字1。其餘的從C1-K1是空的。我試圖糾正這一點,但我確實按照它應該做到的。再次感謝! –

+0

這很奇怪,我不能重現這一點。如果您仍然對答案感到滿意,您可以通過點擊選項 – sodawillow

+0

下的標記將其標記爲已接受。我用花括號做了一個小錯誤。我解決了我的問題。再次感謝你! –