Search code examples
c#powerpointoffice-interop

Set default font for PowerPoint tables


I can create PowerPoint tables with many cells, but the default font (28 points) is too large. Without access to the user's PowerPoint template, how can I set the font for a table I have created? All I can do at the moment is:

  1. Create the table.
  2. Fill every cell with a single space because otherwise font changes are ignored (though it works using the PowerPoint UI).
  3. Create a range containing all cells and set font:

    List<string> names = new List<string>();
    foreach (PowerPoint.Column column in table.Columns)
        foreach (PowerPoint.Cell cell in column.Cells) {
            cell.Shape.TextFrame.TextRange.Text = "";
            names.Add(cell.Shape.Name);
        }
    PowerPoint.ShapeRange range = ppt.ActivePresentation.Slides.Item(1).Shapes.Range(names.ToArray());
    range.TextFrame.TextRange.Font.Size = 12;
    

I am using C# to control PowerPoint 2003..2010 via its COM API. My experiments have been with PowerPoint 2003.


Solution

  • In PPT 2010, this works w/o having to enter text into the cells (vba, but should be easy enough to translate). For demo purposes, I'm working with the currently selected table; substitute any other reference to the table as oTbl:

    Dim oTbl As Table
    Dim lCol As Long
    Dim lRow As Long
    
    
    Set oTbl = ActiveWindow.Selection.ShapeRange(1).Table
    
    With oTbl
        For lCol = 1 To .Columns.Count
            For lRow = 1 To .Rows.Count
                .Cell(lRow, lCol).Shape.TextFrame.TextRange.Font.Size = 28
            Next
        Next
    End With
    

    In PPT2003, as you've seen, you need to add text to the cell for the formatting to "take" (which seriously slows things down, unfortunately).

    Because there are other instances in PPT automation where you may need to temporarily fill in text then delete it, you might want to write a more general routine that you can pass a shape to.

    With Shape.TextFrame.TextRange
      If Len(.Text) = 0 Then
        .Text = "!@#$%" ' or some other lunatic string not likely to be found in nature
      End If
    End With
    

    "Pre-treat" the shape with this, do whatever's necessary, then "Un-treat" it with a companion routine that tests to see if the text = "!@#$%" and sets it back to "" if so, leaves it alone otherwise.