python pptx获取表格宽度

时间:2016-11-07 12:31:22

标签: python python-2.7 python-pptx

我使用python 2.7并使用python pptx。

我在幻灯片中添加了一个表格,需要获得表格的整体宽度。

我找到here _column属性宽度,并尝试使用它,例如使用该代码

for col in table._column:
    yield col.width

并收到以下错误:

AttributeError:'表'对象没有属性' _column'

我需要获取表格宽度(或列宽度并将其相加)。想法?

谢谢!

2 个答案:

答案 0 :(得分:1)

Table上所需的媒体资源为.columns,因此:

for column in table.columns:
    yield column.width

文档的API部分提供了每个属性和每个属性的描述,例如,此页面描述了表对象API: http://python-pptx.readthedocs.io/en/latest/api/table.html

答案 1 :(得分:0)

基于Scanny的代码和pptx documentation,我们可以定义一个函数来打印整个现有python-pptx表对象的尺寸:

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)