Python輕松實現(xiàn)PowerPoint表格的創(chuàng)建與格式化操作

在制作商務(wù)演示文稿時,表格是展示結(jié)構(gòu)化數(shù)據(jù)的重要工具。無論是財務(wù)報表、項目進(jìn)度還是對比分析,清晰規(guī)范的表格都能有效提升信息傳達(dá)效率。通過 Python 自動化生成 PowerPoint 表格,可以批量處理數(shù)據(jù)、保持格式一致性,并大幅減少手動操作時間。
本文介紹如何使用 Spire.Presentation for Python 庫在 PowerPoint 幻燈片中創(chuàng)建表格,并對表格樣式、邊框、單元格合并以及文本對齊等屬性進(jìn)行自定義設(shè)置。該方案適用于需要動態(tài)生成報表、自動化演示文稿制作或批量導(dǎo)出數(shù)據(jù)分析結(jié)果的場景。
環(huán)境準(zhǔn)備
首先需要安裝 Spire.Presentation for Python 庫:
pip install Spire.Presentation
該庫提供了完整的 PowerPoint 文檔操作 API,支持創(chuàng)建、讀取、修改和轉(zhuǎn)換 PPT/PPTX 文件,無需安裝 Microsoft PowerPoint 應(yīng)用程序。
核心實現(xiàn)
創(chuàng)建表格并填充數(shù)據(jù)
創(chuàng)建表格的第一步是定義表格的列寬和行高,然后將其添加到幻燈片中。以下示例展示了如何創(chuàng)建一個包含國家信息的表格:
from spire.presentation.common import *
from spire.presentation import *
import math
# 創(chuàng)建 PowerPoint 文檔
presentation = Presentation()
# 定義表格列寬和行高(單位:磅)
widths = [100, 100, 150, 100, 100]
heights = [15] * 13
# 計算表格位置(水平居中)
left = math.trunc(presentation.SlideSize.Size.Width / 2) - 275
# 在幻燈片中添加表格
table = presentation.Slides[0].Shapes.AppendTable(left, 90, widths, heights)
# 準(zhǔn)備表格數(shù)據(jù)
dataStr = [
["Name", "Capital", "Continent", "Area", "Population"],
["Venezuela", "Caracas", "South America", "912047", "19700000"],
["Bolivia", "La Paz", "South America", "1098575", "7300000"],
["Brazil", "Brasilia", "South America", "8511196", "150400000"],
["Canada", "Ottawa", "North America", "9976147", "26500000"],
["Chile", "Santiago", "South America", "756943", "13200000"]
]
# 填充表格數(shù)據(jù)
for i in range(len(dataStr)):
for j in range(len(dataStr[i])):
table[j, i].TextFrame.Text = dataStr[i][j]
# 設(shè)置字體
table[j, i].TextFrame.Paragraphs[0].TextRanges[0].LatinFont = TextFont("Arial Narrow")
# 保存文檔
presentation.SaveToFile("CreateTable.pptx", FileFormat.Pptx2010)
presentation.Dispose()
結(jié)果文檔:

上述代碼通過 AppendTable 方法在指定位置創(chuàng)建表格,該方法接受四個參數(shù):左邊距、上邊距、列寬數(shù)組和行高數(shù)組。表格創(chuàng)建后,通過二維索引 [列, 行] 訪問每個單元格,并使用 TextFrame.Text 屬性設(shè)置單元格內(nèi)容。
應(yīng)用表格預(yù)設(shè)樣式
Spire.Presentation 提供了多種預(yù)設(shè)表格樣式,可以快速美化表格外觀。預(yù)設(shè)樣式包括不同的顏色主題和格式組合:
from spire.presentation.common import *
from spire.presentation import *
# 加載現(xiàn)有文檔
ppt = Presentation()
ppt.LoadFromFile("CreateTable.pptx")
# 獲取表格對象
table = None
for shape in ppt.Slides[0].Shapes:
if isinstance(shape, ITable):
table = shape
break
if table is not None:
# 應(yīng)用預(yù)設(shè)樣式
table.StylePreset = TableStylePreset.MediumStyle1Accent2
# 其他常用預(yù)設(shè)樣式:
# TableStylePreset.LightStyle3Accent1
# TableStylePreset.DarkStyle1Accent2
# TableStylePreset.MediumStyle2Accent3
# 保存文檔
ppt.SaveToFile("StyledTable.pptx", FileFormat.Pptx2010)
ppt.Dispose()
結(jié)果文檔:

StylePreset 屬性接受 TableStylePreset 枚舉值,這些預(yù)設(shè)樣式已經(jīng)配置好了背景色、邊框、字體顏色等屬性。選擇合適的預(yù)設(shè)樣式可以快速實現(xiàn)專業(yè)的視覺效果。
自定義表格邊框
除了使用預(yù)設(shè)樣式,還可以精確控制表格邊框的顏色、寬度和類型:
from spire.presentation.common import *
from spire.presentation import *
# 創(chuàng)建新文檔
presentation = Presentation()
# 定義表格尺寸
tableWidth = [100, 100, 100, 100, 100]
tableHeight = [20, 20]
# 遍歷所有邊框類型并設(shè)置樣式
for item in TableBorderType:
# 在新幻燈片中添加表格
itable = presentation.Slides.Append().Shapes.AppendTable(100, 100, tableWidth, tableHeight)
# 添加示例文本
itable.TableRows[0][0].TextFrame.Text = "Row"
itable.TableRows[1][0].TextFrame.Text = "Column"
# 設(shè)置邊框:類型、寬度(磅)、顏色
itable.SetTableBorder(item, 1.5, Color.get_Red())
# 保存文檔
presentation.SaveToFile("CustomBorders.pptx", FileFormat.Pptx2013)
presentation.Dispose()
SetTableBorder 方法允許針對不同類型的邊框(如內(nèi)部橫框、內(nèi)部豎框、外邊框等)分別設(shè)置樣式。TableBorderType 枚舉包含以下常用值:
InsideHorizontal:內(nèi)部水平邊框InsideVertical:內(nèi)部垂直邊框Top:頂部邊框Bottom:底部邊框Left:左邊框Right:右邊框
合并單元格
在處理復(fù)雜表格布局時,經(jīng)常需要合并相鄰單元格以創(chuàng)建標(biāo)題行或分組區(qū)域:
from spire.presentation.common import *
from spire.presentation import *
# 加載文檔
presentation = Presentation()
presentation.LoadFromFile("CreateTable.pptx")
# 獲取表格
table = None
for shape in presentation.Slides[0].Shapes:
if isinstance(shape, ITable):
table = shape
break
if table is not None:
# 垂直合并:合并第一列的第2行和第3行
table.MergeCells(table[0, 1], table[0, 2], False)
# 水平合并:合并第5行的第4列和第5列
table.MergeCells(table[3, 4], table[4, 4], True)
# 保存文檔
presentation.SaveToFile("MergedCells.pptx", FileFormat.Pptx2010)
presentation.Dispose()
MergeCells 方法接受三個參數(shù):起始單元格、結(jié)束單元格和合并方向標(biāo)志。第三個參數(shù)為 True 時表示水平合并,False 表示垂直合并。合并后的單元格將保留起始單元格的內(nèi)容和格式。
設(shè)置文本對齊方式
表格中文本的對齊方式直接影響可讀性和美觀度??梢酝瑫r設(shè)置水平和垂直對齊:
from spire.presentation.common import *
from spire.presentation import *
# 加載文檔
presentation = Presentation()
presentation.LoadFromFile("CreateTable.pptx")
# 獲取表格
table = None
for shape in presentation.Slides[0].Shapes:
if isinstance(shape, ITable):
table = shape
break
if table is not None:
# 水平對齊設(shè)置
# 左對齊
table[0, 1].TextFrame.Paragraphs[0].Alignment = TextAlignmentType.Left
# 居中對齊
table[0, 2].TextFrame.Paragraphs[0].Alignment = TextAlignmentType.Center
# 右對齊
table[0, 3].TextFrame.Paragraphs[0].Alignment = TextAlignmentType.Right
# 兩端對齊
table[0, 4].TextFrame.Paragraphs[0].Alignment = TextAlignmentType.Justify
# 垂直對齊設(shè)置
# 頂部對齊
table[1, 1].TextAnchorType = TextAnchorType.Top
# 垂直居中
table[1, 2].TextAnchorType = TextAnchorType.Center
# 底部對齊
table[1, 3].TextAnchorType = TextAnchorType.Bottom
# 同時設(shè)置水平和垂直對齊
table[2, 1].TextFrame.Paragraphs[0].Alignment = TextAlignmentType.Left
table[2, 1].TextAnchorType = TextAnchorType.Top
# 保存文檔
presentation.SaveToFile("AlignedTable.pptx", FileFormat.Pptx2010)
presentation.Dispose()
水平對齊通過 TextFrame.Paragraphs[0].Alignment 屬性設(shè)置,接受 TextAlignmentType 枚舉值。垂直對齊通過 TextAnchorType 屬性設(shè)置,控制文本在單元格垂直方向的定位。
功能演示
綜合示例:創(chuàng)建完整格式的表格
將上述功能組合使用,可以創(chuàng)建具有專業(yè)外觀的完整表格:
from spire.presentation.common import *
from spire.presentation import *
import math
# 創(chuàng)建文檔
presentation = Presentation()
# 定義表格結(jié)構(gòu)
widths = [120, 100, 100, 100]
heights = [20, 18, 18, 18, 18]
# 添加表格
left = math.trunc(presentation.SlideSize.Size.Width / 2) - 210
table = presentation.Slides[0].Shapes.AppendTable(left, 80, widths, heights)
# 填充數(shù)據(jù)
headers = ["產(chǎn)品", "Q1", "Q2", "Q3"]
products = [
["產(chǎn)品A", "150", "180", "210"],
["產(chǎn)品B", "120", "140", "160"],
["產(chǎn)品C", "90", "110", "130"]
]
# 設(shè)置表頭
for j in range(len(headers)):
table[j, 0].TextFrame.Text = headers[j]
table[j, 0].TextFrame.Paragraphs[0].Alignment = TextAlignmentType.Center
table[j, 0].TextFrame.Paragraphs[0].TextRanges[0].Fill.FillType = FillFormatType.Solid
table[j, 0].TextFrame.Paragraphs[0].TextRanges[0].Fill.SolidColor.Color = Color.get_White()
# 設(shè)置數(shù)據(jù)行
for i in range(len(products)):
for j in range(len(products[i])):
table[j, i + 1].TextFrame.Text = products[i][j]
if j == 0:
table[j, i + 1].TextFrame.Paragraphs[0].Alignment = TextAlignmentType.Left
else:
table[j, i + 1].TextFrame.Paragraphs[0].Alignment = TextAlignmentType.Center
# 應(yīng)用樣式
table.StylePreset = TableStylePreset.MediumStyle2Accent3
# 設(shè)置邊框
table.SetTableBorder(TableBorderType.InsideHorizontal, 0.5, Color.get_Gray())
table.SetTableBorder(TableBorderType.InsideVertical, 0.5, Color.get_Gray())
table.SetTableBorder(TableBorderType.Top, 1.5, Color.get_DarkBlue())
table.SetTableBorder(TableBorderType.Bottom, 1.5, Color.get_DarkBlue())
# 保存文檔
presentation.SaveToFile("CompleteTable.pptx", FileFormat.Pptx2010)
presentation.Dispose()
此示例綜合運(yùn)用了數(shù)據(jù)填充、樣式應(yīng)用、邊框設(shè)置和對齊控制,生成了一個具有清晰層次結(jié)構(gòu)的銷售數(shù)據(jù)表格。表頭使用白色字體突出顯示,數(shù)據(jù)按類別左對齊、數(shù)值居中對齊,整體采用中等強(qiáng)度的強(qiáng)調(diào)色主題。
實用技巧
調(diào)整行高和列寬
創(chuàng)建表格后,可以根據(jù)內(nèi)容動態(tài)調(diào)整單元格尺寸:
# 設(shè)置特定行的行高
table.TableRows[0].Height = 25
# 設(shè)置特定列的列寬
table.ColumnsList[0].Width = 150
# 批量設(shè)置所有行高
for row in table.TableRows:
row.Height = 20
填充單元格背景色
可以為特定行或單元格設(shè)置背景色以突出重要信息:
# 為整行設(shè)置背景色
for cell in table.TableRows[1]:
cell.Fill.FillType = FillFormatType.Solid
cell.Fill.SolidColor.Color = Color.get_LightYellow()
# 為單個單元格設(shè)置背景色
table[0, 2].Fill.FillType = FillFormatType.Solid
table[0, 2].Fill.SolidColor.Color = Color.get_LightGreen()
識別合并單元格
在處理現(xiàn)有表格時,可能需要檢測哪些單元格已被合并:
# 遍歷所有單元格,識別合并狀態(tài)
for i in range(table.ColumnsList.Count):
for j in range(table.TableRows.Count):
cell = table[i, j]
if cell.IsMergedCell:
print(f"單元格 [{i}, {j}] 是合并單元格")
總結(jié)
本文介紹了使用 Python 在 PowerPoint 中創(chuàng)建和格式化表格的完整流程,涵蓋了從基礎(chǔ)的數(shù)據(jù)填充到高級的樣式定制。通過 Spire.Presentation 庫,可以靈活控制表格的各個方面:
- 使用
AppendTable方法創(chuàng)建表格并定義尺寸 - 通過
StylePreset快速應(yīng)用預(yù)設(shè)樣式 - 使用
SetTableBorder精確控制邊框樣式 - 通過
MergeCells實現(xiàn)復(fù)雜的單元格布局 - 利用
Alignment和TextAnchorType優(yōu)化文本排版
這些技術(shù)可以應(yīng)用于自動化報表生成、批量演示文稿制作和數(shù)據(jù)可視化場景。結(jié)合其他 PowerPoint 自動化功能,如形狀、圖表和 SmartArt,可以構(gòu)建更加豐富和專業(yè)的演示內(nèi)容。
以上就是Python輕松實現(xiàn)PowerPoint表格的創(chuàng)建與格式化操作的詳細(xì)內(nèi)容,更多關(guān)于Python PowerPoint表格操作的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python的Flask框架中Flask-Admin庫的簡單入門指引
這篇文章主要介紹了一個Python的Flask框架中Flask-Admin庫簡單入門的指引,包括介紹和簡單的部署等,需要的朋友可以參考下2015-04-04
Django動態(tài)隨機(jī)生成溫度前端實時動態(tài)展示源碼示例
本篇文章主要描述的是在動態(tài)隨機(jī)生成溫度,在前端動態(tài)實時展示,主要用到兩個東西,一個是APScheduler定時任務(wù) 和websocket,最后利用echarts將數(shù)據(jù)展示出來,下面對這兩個分別進(jìn)行詳細(xì)的解說2021-09-09
PyTorch之torch.matmul函數(shù)的使用及說明
PyTorch的torch.matmul是一個強(qiáng)大的矩陣乘法函數(shù),支持不同維度張量的乘法運(yùn)算,包括廣播機(jī)制。提供了矩陣乘法的語法,參數(shù)說明,以及使用示例,幫助理解其應(yīng)用方式和乘法規(guī)則2024-09-09
Python?flask框架post接口調(diào)用示例
這篇文章主要介紹了Python?flask框架post接口調(diào)用,結(jié)合實例形式分析了基于flask框架的post、get請求響應(yīng)及接口調(diào)用相關(guān)操作技巧,需要的朋友可以參考下2019-07-07
Python多任務(wù)版靜態(tài)Web服務(wù)器實現(xiàn)示例
這篇文章主要為大家介紹了Python靜態(tài)Web服務(wù)器多任務(wù)版實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
基于循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)實現(xiàn)影評情感分類
這篇文章主要為大家詳細(xì)介紹了基于循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)實現(xiàn)影評情感分類,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03
Python爬蟲爬取一個網(wǎng)頁上的圖片地址實例代碼
這篇文章主要介紹了Python爬蟲爬取一個網(wǎng)頁上的圖片地址實例代碼,具有一定借鑒價值,需要的朋友可以參考下2018-01-01

