我在读取多个文本文件并尝试添加后创建了一个doc文件
Powershell 中文档文件中对应页面标题的文本文件名
但是下面的代码将最后读取的文件写为每页的标题。
注意:-数据显示在doc文件上正确,只有 header 未正确写入。
如何将文本文件名写为doc的 header (意味着同一doc在不同页面上将具有不同的 header )
$dir="D:\abcd"
$val=ls $dir
$file_count=(get-childitem .).count
$page_count=0
$hash=@{};
set-variable -name wdAlignPageNumberCenter -value 1
$Word = New-Object -ComObject Word.Application
$Word.Visible = $true
$Doc = $Word.Documents.Add()
$Section = $Doc.Sections.Item(1)
$Header = $Section.Headers.Item(1)
$Footer = $Section.Footers.Item(1)
$Footer.PageNumbers.Add($wdAlignPageNumberCenter)
$selection=$word.Selection
$page="`tPage";
$loop=1
foreach ($file in $val){
$filename = "D:\abcd\$file"
$filedata = (get-content $filename);
$Footer.Range.Text=$page
$head="ABCD`t`tFile ID: $file"
$Header.Range.Text = $head
}
$savepath="D:\abcd\$file.docx"
$Doc.SaveAs([ref]$savepath)
$Doc.Close()
最佳答案
在Word中,可以通过section拆分文档的不同部分来创建唯一的标题。您遇到的问题是因为似乎只有一个部分,所以也将只有一个 header ...在foreach
循环中被覆盖了。此行为与您描述的结果一致,因为最后读取的文件将作为整个文档的标题出现,这才有意义。
您已经在此处指定了一个部分(和一组页眉/页脚):
$Section = $Doc.Sections.Item(1)
$Header = $Section.Headers.Item(1)
$Footer = $Section.Footers.Item(1)
每次需要不同的标题时,只需修改逻辑以创建一个新的逻辑即可。
关于powershell - 在PowerShell中的Word文档文件的不同页面上的不同标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18981319/