使用powershell能够像这样在表格单元格中添加文本,现在我想格式化单元格文本。
table.Cell(1,1).Range.Text ="列出vItem1
vitem2"
例如。 我想大胆并调整中心" List"串。为Item1和Iteam2字符串应用有序项目样式。 我怎么能用powershell做到这一点?
编辑: 在C#中找到了这个代码,无法在PowerShell中使用它。
//boldrange_1 for "green", boldrange_2 for "inch".
Word.Range boldrange_1 = table.Cell(1, 2).Range;//Assign the whole cell range to boldrange, then adjust it with SetRange method.
boldrange_1.SetRange(table.Cell(1, 2).Range.Start, table.Cell(1, 2).Range.Words[1].End);
boldrange_1.Bold= 1;
Word.Range boldrange_2 = table.Cell(2, 2).Range;
boldrange_2.SetRange(table.Cell(2, 2).Range.Words[4].End, table.Cell(2, 2).Range.Words[5].End);
boldrange_2.Font.Bold = 1;
//I've found that boldrange_2.Font.Bold = 1; and boldrange_2.Bold = 1; have the same effect.
答案 0 :(得分:1)
将字体设置为粗体或正常实际上并不那么难,是的只需要使用设置范围。将对齐或设置单词更改为列表有点棘手,因为您必须在单独的段落中设置元素,并且典型的方法(使用TypeParagraph与TypeText)将无法在表格单元格中工作。此方法适用于我,但段落设置和表格设置需要根据您的特定需求进行更改。
#This is just creating a simple table for testing
$w = New-Object -ComObject "word.application"
$w.Visible = $true
$doc = $w.Documents.add()
$r = $doc.Range()
$table = $doc.Tables.add($r, 5, 5)
$list = $table.Cell(1,1).Range #so sel doesn't have to be rewritten by hyperlinks
$sel = $table.Cell(1,1).Range #this is because the hyperlinks break indexof
$hyper = $table.Cell(1,1).Range #doing assign this way for emphasis could do easier
#Define full text for spliting up into ranges and setup paragraphs
$sel.InsertParagraph()
$w.Selection.TypeText("HyperLink`n`rList`r`nItem1`r`nItem2")
#Set up the hyperlink (use -2 to keep `n`r for paragraph)
$hyper.SetRange(0, $sel.Text.IndexOf("List") - 2)
$list.SetRange($sel.Text.IndexOf("List"), $sel.Text.Length)
$sel.SetRange($sel.Text.IndexOf("Item"), $sel.Text.Length)
$doc.Hyperlinks.Add($hyper, 'www.google.com', $null, $null, "Link to Google")
#set List range of cell to bold and alignment center
$list.Bold = $true
$list.paragraphFormat.Alignment = 'wdAlignParagraphCenter'
#Now using sel range: add paragraph break (so list only applies to this)
#Then set alignment and apply a number list
$sel.InsertParagraphBefore()
$sel.paragraphFormat.Alignment = 'wdAlignParagraphRight'
$sel.ListFormat.ApplyNumberDefault()
更新:清理代码并添加超链接构建方法