python pptx determine a table width and height

Question:

I use python 2.7 with python pptx.

I have a table of data and need it to feet certain width and height,

I learned that i can change the text size like so enter link description here

But i wish to change the entire table size to fit an exact location and with changing the font size, and manipulating the row heights and col width it all seems too complex and hard to handle,

I found that i can turn the table to an image and than easily change it’s size but that does not feel like the right thing to do.

Ideas?

Asked By: thebeancounter

||

Answers:

The example taken from the pptx documentation gives a good example on how to create a table with a given overall width and height as follows:

from pptx import Presentation
from pptx.util import Inches

prs = Presentation()
title_only_slide_layout = prs.slide_layouts[5]
slide = prs.slides.add_slide(title_only_slide_layout)
shapes = slide.shapes

shapes.title.text = 'Adding a Table'

rows = cols = 2
left = top = Inches(2.0)
width = Inches(6.0)
height = Inches(0.8)

table = shapes.add_table(rows, cols, left, top, width, height).table

# set column widths
table.columns[0].width = Inches(2.0)
table.columns[1].width = Inches(4.0)

# write column headings
table.cell(0, 0).text = 'Foo'
table.cell(0, 1).text = 'Bar'

# write body cells
table.cell(1, 0).text = 'Baz'
table.cell(1, 1).text = 'Qux'

prs.save('test.pptx')

The util Module also provides alternatives to specifying the dimensions such as Centipoints, Cm, Emu, Mm, Pt and Px.

Answered By: Martin Evans

Actually, we may try to use win32 api provided by MS Office for this issue.
It’s very similar to vba.
Hope this finds you well.

import win32com.client as win32
from win32com.client import constants
# 使用EnsureDispatch方法创建PowerPoint应用程序对象
#Use EnsureDispatch Method
ppt = win32.gencache.EnsureDispatch('PowerPoint.Application')
# iterate through all tables in the active document
for slide in ppt.ActivePresentation.Slides:
    for shape in slide.Shapes:
        # find out if there's a table in the slide
        if shape.HasTable == -1:
            table = shape.Table
            # Set the table width to 24cm, We can divide the number of centimetres by 0.035278 to get the number of points.
            shape.Width = 24 / 0.035278
            # Set the table height to 24cm
            shape.Height = 24 / 0.035278
            # Set the height of the first row of the table to 1cm
            table.Rows(1).Height = 1 / 0.035278

Visit Microsoft VBA Reference Document for more info.

Answered By: Jugfl
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.