0

I work with python 2.7 and using python pptx.

I add a table to my slide, and need to get the table overall width.

I found here the _column attribute width, and try to use it, for example with that code

for col in table._column:
    yield col.width

and get the following error:

AttributeError: 'Table' object has no attribute '_column'

I need to get the table width (or the columns width and sum it). ideas?

Thanks!

thebeancounter
  • 4,261
  • 8
  • 61
  • 109

2 Answers2

1

The property you want on Table is .columns, so:

for column in table.columns:
    yield column.width

All the properties and a description of each is available in the API section of the documentation, for example this page describing the table object API: http://python-pptx.readthedocs.io/en/latest/api/table.html

scanny
  • 26,423
  • 5
  • 54
  • 80
0

Building off Scanny's code and the pptx documentation we can define a function like this to print the dimensions of an entire existing python-pptx table object:

from pptx import Presentation
from pptx.util import Inches, Cm, Pt

def table_dims(table, measure = 'Inches'):
    """
    Returns a dimensions tuple (width, height) of your pptx table 
    object in Inches, Cm, or Pt. 
    Defaults to Inches.
    This value can then be piped into an Inches, Cm, or Pt call to 
    generate a new table of the same initial size. 
    """

    widths = []
    heights = []

    for column in table.columns:
        widths.append(column.width)
    for row in table.rows:
        heights.append(row.height)

    # Because the initial widths/heights are stored in a strange format, we'll convert them
    if measure == 'Inches':
        total_width = (sum(widths)/Inches(1)) 
        total_height = (sum(heights)/Inches(1))
        dims = (total_width, total_height)
        return dims

    elif measure == 'Cm':
        total_width = (sum(widths)/Cm(1))
        total_height = (sum(heights)/Cm(1))
        dims = (total_width, total_height)
        return dims

    elif measure == 'Pt':
        total_width = (sum(widths)/Pt(1))
        total_height = (sum(heights)/Pt(1))
        dims = (total_width, total_height)
        return dims

    else:
        Exception('Invalid Measure Argument')

# Initialize the Presentation and Slides objects
prs = Presentation('path_to_existing.pptx')
slides = prs.slides

# Access a given slide's Shape Tree
shape_tree = slides['replace w/ the given slide index'].shapes

# Access a given table          
table = shape_tree['replace w/ graphic frame index'].table

# Call our function defined above
slide_table_dims = table_dims(table)
print(slide_table_dims)
jkix
  • 184
  • 1
  • 2
  • 17