使用python pptx自动调整列宽

时间:2017-06-01 12:22:05

标签: python python-pptx

我已经将一个表插入到pptx文件中,我想自动调整列宽,以便列单元格中的所有文本都不需要断行。所以我只是在寻找整个专栏的自动调整。

到目前为止我所拥有的是:

from pptx import Presentation
from pptx.util import Inches
from PandasToPowerpoint import df_to_table
import pandas as pd

d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
     'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
prs = Presentation()
title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layout)

top = Inches(2.5)
left = Inches(0.48)
width = Inches(12.3)
height = Inches(3.0) 
df_to_table(slide, df.reset_index(), left, top, width, height)


for shape in slide.shapes:
    if shape.has_table:
        table = shape.table
        for column in table.columns: 
            column.width=Inches(3)

prs.save('test.pptx')   

我试过了:

column.text_frame.auto_size = True
column.auto_size = True
column.fit_text= True

但它们都不起作用。如果autoadjust不起作用,我还可以遍历列的所有单元格并识别具有最长文本的单元格,并将整个列宽度调整为此文本。但是我也找不到正确的命令来获得文本宽度......任何想法都值得赞赏!

1 个答案:

答案 0 :(得分:1)

我知道您正在寻找调整列宽的解决方案,但是如何调整行高:

import pptx.enum.text MSO_AUTO_SIZE

table.cell(row, column).text_frame.auto_size = MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT