首页 > 解决方案 > Powershell在与文本混合的Word文档中添加多个风格化表格

问题描述

本质上,我正在制作一张发票清单作为账单,它看起来像这样(通过 powershell 使用 word,注意 word 文件不会预先存在,我创建一个新文件并开始添加): 在此处输入图像描述

问题是我只知道如何执行以下操作:

$word = New-Object -comobject word.application
$word.Visible = $false
$doc = $word.Documents.Add()
$Selection = $word.Selection
$Selection.Style="Title"
$Selection.Font.Bold = 1
$Selection.ParagraphFormat.Alignment = 2
$Selection.TypeText("Expected Billing")
$Selection.TypeParagraph()
$Selection.Style="No Spacing"
$Selection.Font.Bold = 0
$Selection.TypeParagraph()
$doc.SaveAs([ref]$savepath) 
$doc.Close() 
$word.quit()

添加文本很容易,但在添加表格时,我无法正确处理。如你看到的:

实际上,编号的表格也不应该有边框,但我把它们留下了,所以你可以直观地看到。然后当然是我可以做的总计算量。但请注意它出现在表格之后,所以我想要追加表格并想知道如何在它们之后追加。有人可以帮我吗?我不知道这个的编码。

标签: powershellms-wordcomobjectword-table

解决方案


好的,经过更多研究,我想通了。我将发布代码

    $Range = $Selection.Range
    $Table = $Selection.Tables.add($Selection.Range,2,5)
    $Table.cell(1,1).range.text = "Item Code"
    $Table.cell(2,1).range.text = "Description"

    $Table.cell(1,2).range.text = "Quantity"
    $Table.cell(1,3).range.text = "Amount"
    $Table.cell(1,4).range.text = "SUP"
    $Table.cell(1,5).range.text = "Dealer Code"
    $Selection.EndKey(6) | Out-Null

您必须从添加开始并确保以 End Key(6) 结束

要编辑宽度或字体样式:

   $Table.cell(1,1).Width = 222.2 
   $Table.cell(1,1).range.Font.bold = 1 

推荐阅读