[英]How to modify existing tables in powerpoint using pandas and python-pptx?
您必須編寫一個簡短的例程來逐個單元地執行此操作。 PowerPoint 表格中的每個單元格都是一個文本容器,API 中沒有“從序列(矩陣)序列填充此表格的單元格”方法。
請注意,所有值都必須是str
類型(如果您使用的是 Python 2,則必須是unicode
類型)。 PowerPoint 表格沒有 Excel 那樣的數字或公式概念。 每個單元格只包含文本。
像這樣的事情在簡單的情況下可以解決問題,但是您已經可以看到可能存在復雜性,例如“如果我想跳過標題行怎么辦”或“如果矩陣與表格的大小不同怎么辦”,或“如果我想根據列格式化具有特定小數位的數字怎么辦”等。
M = {"matrix", some sequence of sequences like a `numpy` array or list of lists}
table = {"table" object retrieved from a shape on a slide}
populate_table(table, M)
def populate_table(table, M):
for row in range(len(M)):
row_cells = table.rows[row].cells
for col in range(len(M[0]):
row_cells[col].text = str(M[row][col])
所涉及的代碼很小且易於定制,設計然后使用通用解決方案的復雜性相當高,因此這由用戶自己解決。
沒有什么能阻止您創建自己的函數,例如上面的populate_table(matrix, table)
並在適合您的任何地方使用它。
下載 pptx-tables @ https://github.com/bharath5673/python-pptx-tables
from pptx import Presentation
from pptx.util import Inches, Pt
from pptx_tables import PptxTable
prs=Presentation()
prs.slide_width = Inches(13.333)
prs.slide_height = Inches(7.5)
data = [
[['Aa', 'Bb','Cc'],
[3, 4, 5],
[6, 7, 8]],
[['Dd', 'Ee','Ff'],
[0, 1, 2],
[6, 7, 8]]
]
for n,lst in enumerate(data):
lyt=prs.slide_layouts[6] # choosing a slide layout
slide=prs.slides.add_slide(lyt) # adding a slide
# title=slide.shapes.title
title_name = f"Page : "+str(n)
# title.text=title_name
# subtitle=slide.placeholders[1]
tbl = PptxTable(lst,prs)
tbl.set_table_location(left=Inches(1.5), top=Inches(2), width=Inches(5))
# tbl.set_formatting(font_size=Pt(7), row_height=Inches(.3),alignment=PP_PARAGRAPH_ALIGNMENT.LEFT)
tbl.set_formatting(font_size=Pt(12), row_height=Inches(.85))
tbl.create_table(slide_index=n,
columns_widths_weight=[2, 2, 2],
transpose=True,
)
tbl.save_pptx("slide_table.pptx")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.