PowerShell 写入word

文章目录[隐藏]

在此之前对Word文档使用编辑之前,我们需要将文档添加到Word对象,然后选择它,以便我们可以向其添加文本。

$doc = $word.documents.Add()
$myDoc = $word.Selection

如果我们使用TypeText方法,我们需要理解的文本将与文本的其余部分出现在同一行上。因此,我们需要使用 TypeParagraph 方法,该方法用于从新行(如 HTML 中的换行标记)开始,然后使用 TypeText 开始在全新的行上写入。

$myDoc.Style=”Strong”
$myDoc.TypeParagraph()
$myDoc.TypeText(“Hi All, “)
$myDoc.TypeParagraph()
$myDoc.TypeText(“This is Message from dotnet-helpers.com “)

最终代码

####################################################### 
#Project : Writing in Word doc using Powershell 
#Developer : Thiyagu S (dotnet-helpers.com)
#Tools : PowerShell 5.1.15063.1155 
#E-Mail : mail2thiyaguji@gmail.com 
####################################################### 
 
$savepath="C:\dotnet-helpers\ReviewCommends.docx" 
 
$word=new-object -ComObject "Word.Application"
$Word.Visible = $True
 
$doc = $word.documents.Add() 
$myDoc = $word.Selection
 
$myDoc.Style="Strong" 
$myDoc.Font.Bold = 1
$myDoc.TypeParagraph()
$myDoc.TypeText("Hi All, ") 
$myDoc.TypeParagraph()
$myDoc.TypeText("This is Message from dotnet-helpers.com ")
 
$myDoc.Style="Normal" 
$myDoc.Font.Italic = 1
$myDoc.TypeParagraph() 
$myDoc.TypeText("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes,nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu,
pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel,aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae") 
 
$myDoc.TypeParagraph() 
$myDoc.TypeParagraph() 
$myDoc.TypeText("Thanks") 
$myDoc.TypeParagraph() 
$myDoc.Style="Strong" 
$myDoc.TypeText("Thiyagu S") 
$myDoc.TypeParagraph() 
$Date = Get-Date 
$myDoc.TypeText("Date: $($Date)") 
 
$doc.SaveAs([ref]$savepath) 
$doc.Close() 
 
$word.quit() 
Invoke-Item $savepath
 
#Here you want to release all of these objects, so here we call the ReleaseComObject method, so we doing this each of objects which created. 
#then you need to call garbage collection to scavenge memory, and I remove the variables.
 
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($doc) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
Remove-Variable doc,Word
[gc]::collect()
[gc]::WaitForPendingFinalizers()

输出

Getting_Started_with_Word_Using_PowerShell_dotnet-helper_thiyagu_50

 

相关推荐

onenote 使用教程

OneNote 是一款由微软开发的数字笔记应用,它可以让你在一个位置收集你的所有笔记、研究、计划和信息,无论这 ...