乘法表PowerShell

我正在试图通过使用嵌套for循环将在Excel中打开一个乘法表10×10。 到目前为止,我已经打开了excel:

$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格式表格显示,而是在另一个下面显示。 有人可以帮我把这个放在一起,或给我一些提示如何使其工作?

  • 你的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 } } 

试试这个,告诉我是否需要调整。 我会评论这些代码,以便更好地理解。

Interesting Posts