簡體   English   中英

Powershell 從數組填充單詞表

[英]Powershell populate word table from an array

我有一個 PS 腳本,它將 csv 導入多個 arrays,我需要它來填充 word 中的表格。 我能夠將數據放入 arrays,並創建一個包含標題和正確行數的表,但無法將 arrays 中的數據放入表中。 進行大量谷歌搜索后,我找到了以下代碼。 任何幫助是極大的贊賞。

My_File.txt 示例行數會有所不同,但 header 行始終存在。

組件,id,iType,

VCT,AD-1234,故事,

VCT、Ad-4567、DR、

$component = @()
$id = @()
$iType =@()
$vFile = Import-CSV ("H:\My_file.txt")
$word = New-Object -ComObject "Word.Application"

$vFile | ForEach-Object {
$component += $_.components
$id += $_.id
$iType +=_.iType
}

$template = $word.Documents.Open ("H:\Test.docx")

$template = $word.Document.Add()
$word.Visible = $True
$Number_rows = ($vFile.count +1)
$Number_cols = 3

$range = $template.range()
$template.Tables.add($range, $Number_rows, $Number_cols) | out-null

$table = $template.Tables.Item(1)
$table.cell(1,1).Range.Text = "Component"
$table.cell(1,2).Range.Text = "ID"
$table.cell(1,3).Range.text = "Type"

for ($i=0; $i -lt; $vFile.count+2, $i++){
$table.cell(($i+2),1).Range.Text = $component[$i].components
$table.cell(($i+2),2).Range.Text = $id[$i].id
$table.cell(($i+2),3).Range.Text = $iType[$i].iType
}

$Table.Style = "Medium Shading 1 - Accent 1"
$template.SaveAs("H:\New_Doc.docx")

不要將解析后的 CSV object 數組中的行分成三個 arrays,而是保留集合原樣並使用數據直接使用 object 數組的屬性填充表。

我冒昧地將你的變量$vFile重命名為$data至少對我來說這是對其中內容的更多描述。

嘗試

$data = Import-Csv -Path "H:\My_file.txt"
$word = New-Object -ComObject "Word.Application"
$word.Visible = $True

$template = $word.Documents.Open("H:\Test.docx")
$Number_rows = $data.Count +1  # +1 for the header
$Number_cols = 3

$range = $template.Range()
[void]$template.Tables.Add($range, $Number_rows, $Number_cols)

$table = $template.Tables.Item(1)
$table.Style = "Medium Shading 1 - Accent 1"

# write the headers
$table.cell(1,1).Range.Text = "Component"
$table.cell(1,2).Range.Text = "ID"
$table.cell(1,3).Range.text = "Type"

# next, add the data rows
for ($i=0; $i -lt $data.Count; $i++){
    $table.cell(($i+2),1).Range.Text = $data[$i].component
    $table.cell(($i+2),2).Range.Text = $data[$i].id
    $table.cell(($i+2),3).Range.Text = $data[$i].iType
}

$template.SaveAs("H:\New_Doc.docx")

完成后,不要忘記關閉文檔,退出 word 並清理使用過的 COM 對象:

$template.Close()
$word.Quit()

$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($template)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($word)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM