簡體   English   中英

python pptx獲取表寬度

[英]python pptx get table width

我使用python 2.7並使用python pptx。

我在幻燈片中添加了表格,並需要獲取表格的整體寬度。

我在這里找到_column屬性的寬度,並嘗試使用它,例如與該代碼一起使用

for col in table._column:
    yield col.width

並得到以下錯誤:

AttributeError:“表”對象沒有屬性“ _column”

我需要獲取表的寬度(或列的寬度並求和)。 想法?

謝謝!

您要在Table上使用的屬性是.columns ,因此:

for column in table.columns:
    yield column.width

文檔的API部分提供了所有屬性以及每個屬性的描述,例如,此頁面描述了表對象API: http : //python-pptx.readthedocs.io/zh/latest/api/table.html

基於Scanny的代碼和pptx文檔,我們可以定義一個函數來打印整個現有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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM