我有一個 PS 腳本,它將一個 csv 匯入到幾個陣列中,我需要它來用 word 填充一個表。我能夠將資料放入陣列中,并創建一個帶有標題和正確行數的表,但無法將陣列中的資料放入表中。做了大量的谷歌搜索讓我得到了以下代碼。任何幫助是極大的贊賞。
My_File.txt 的示例 行數會有所不同,但標題行始終存在。
組件,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")
uj5u.com熱心網友回復:
不要將決議后的 CSV 物件陣列中的行分成三個陣列,而是將集合保持原樣,并使用該物件陣列的屬性直接使用資料填充表。
我冒昧地將您的變數重命名$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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/454141.html
