1
votes

Using powershell able add text in the table cell like this, now I want to format the cell text.

table.Cell(1, 1).Range.Text = "ListvItem1vitem2"

eg. I want to bold and align center "List" string. apply ordered item style for Item1 and Iteam2 string. How can I do this using powershell?

Edit: found this code in C#, not able to make it work in powershell.

https://social.msdn.microsoft.com/Forums/vstudio/en-US/4d7fa718-29d7-4b71-848e-11d7aafac5b7/multiple-format-into-one-cell-of-table-in-word-2007-using-c?forum=worddev

 //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.
1

1 Answers

1
votes

Setting the font as bold or normal is not actually that hard, and yes just requires the use of set-range. Changing the alignment or setting words as a list is a bit trickier as you have to set the elements in separate paragraphs and the typical method (using TypeParagraph with TypeText) will not work in a table cell. This method works for me, though the paragraph settings and table setting will need to be altered based on your specific needs.

#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()

Update: Cleaned up code and added hyperlink building method