使用Python在Word文檔中創(chuàng)建表格并設(shè)置各種格式
在現(xiàn)代辦公環(huán)境中,Word 文檔是信息傳遞和報告輸出的重要載體。從制作財務(wù)報表、項目進度表,到創(chuàng)建產(chǎn)品對比清單、員工信息表,表格以其清晰的結(jié)構(gòu)化展示能力,成為各類文檔中不可或缺的元素。然而,當(dāng)需要處理大量數(shù)據(jù)或定期生成標準化報告時,手動在 Word 中創(chuàng)建和格式化表格不僅耗時耗力,還容易出現(xiàn)格式不一致、數(shù)據(jù)錄入錯誤等問題。而 Python 憑借其強大的自動化處理能力,結(jié)合專業(yè)的文檔操作庫,可以高效地實現(xiàn) Word 表格的批量創(chuàng)建、格式化和數(shù)據(jù)填充,大幅提升工作效率。
本文將使用 Free Spire.Doc for Python 展示如何在 Word 文檔中創(chuàng)建基礎(chǔ)表格、設(shè)置表格樣式、合并與拆分單元格、創(chuàng)建嵌套表格等實用功能,結(jié)合實際業(yè)務(wù)場景的數(shù)據(jù)示例,幫助你快速掌握 Word 表格自動化處理技能。
1. 環(huán)境準備與庫安裝
首先需要安裝 Free Spire.Doc for Python:
pip install spire.doc.free
安裝完成后,我們可以開始創(chuàng)建 Word 文檔并準備表格。下面是一個創(chuàng)建 Word 文件的簡單示例:
from spire.doc import *
from spire.doc.common import *
# 創(chuàng)建一個新的 Word 文檔
document = Document()
# 添加一個節(jié)
section = document.AddSection()
# 添加一個段落作為標題
title = section.AddParagraph()
text_range = title.AppendText("員工信息表")
title.Format.HorizontalAlignment = HorizontalAlignment.Center
text_range.CharacterFormat.Bold = True
text_range.CharacterFormat.FontSize = 18
# 保存初始文件
document.SaveToFile("EmployeeTable.docx", FileFormat.Docx)
document.Close()
print("Word 文檔已創(chuàng)建:EmployeeTable.docx")說明:Document 對象代表整個 Word 文檔,AddSection() 方法添加一個新的節(jié),AddParagraph() 方法添加段落。這里我們創(chuàng)建了一個包含標題的文檔,為后續(xù)創(chuàng)建表格做好準備。
2. 創(chuàng)建基礎(chǔ)表格:員工信息管理
假設(shè)我們需要為人力資源部門創(chuàng)建一份員工信息表,包含姓名、部門、職位、入職日期和聯(lián)系方式等字段。我們可以在代碼中直接生成表格并填充數(shù)據(jù):
from spire.doc import *
from spire.doc.common import *
# 創(chuàng)建文檔
document = Document()
section = document.AddSection()
# 添加標題
title = section.AddParagraph()
text_range = title.AppendText("員工信息表")
title.Format.HorizontalAlignment = HorizontalAlignment.Center
text_range.CharacterFormat.Bold = True
text_range.CharacterFormat.FontSize = 18
section.AddParagraph() # 添加空行
# 準備表頭和數(shù)據(jù)
headers = ["姓名", "部門", "職位", "入職日期", "聯(lián)系方式"]
employees = [
["張三", "技術(shù)部", "軟件工程師", "2020-03-15", "13800138001"],
["李四", "市場部", "市場經(jīng)理", "2019-06-20", "13800138002"],
["王五", "人力資源部", "人力資源專員", "2021-01-10", "13800138003"],
["趙六", "財務(wù)部", "會計", "2018-11-05", "13800138004"],
["錢七", "技術(shù)部", "產(chǎn)品經(jīng)理", "2020-08-22", "13800138005"],
]
# 創(chuàng)建表格
table = section.AddTable(True)
table.ResetCells(len(employees) + 1, len(headers))
# 設(shè)置表頭行
header_row = table.Rows[0]
header_row.IsHeader = True
header_row.Height = 30
header_row.HeightType = TableRowHeightType.Exactly
# 填充表頭并設(shè)置樣式
for i, header in enumerate(headers):
cell = header_row.Cells[i]
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
cell.CellFormat.Shading.BackgroundPatternColor = Color.get_Gray()
paragraph = cell.AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
text_range = paragraph.AppendText(header)
text_range.CharacterFormat.Bold = True
text_range.CharacterFormat.FontSize = 12
# 填充數(shù)據(jù)行
for row_idx, employee in enumerate(employees):
data_row = table.Rows[row_idx + 1]
data_row.Height = 25
data_row.HeightType = TableRowHeightType.Exactly
for col_idx, value in enumerate(employee):
cell = data_row.Cells[col_idx]
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
cell.CellFormat.Shading.BackgroundPatternColor = Color.Empty()
paragraph = cell.AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
paragraph.AppendText(value)
# 設(shè)置隔行變色
for row_idx in range(1, table.Rows.Count):
if row_idx % 2 == 0:
row = table.Rows[row_idx]
for cell_idx in range(row.Cells.Count):
cell = row.Cells[cell_idx]
cell.CellFormat.Shading.BackgroundPatternColor = Color.get_LightBlue()
# 保存文檔
document.SaveToFile("EmployeeTable.docx", FileFormat.Docx)
document.Close()
print("員工信息表已創(chuàng)建完成")文檔預(yù)覽:

說明:
通過 section.AddTable(True) 創(chuàng)建表格,ResetCells() 方法設(shè)置表格的行數(shù)和列數(shù)。我們?yōu)楸眍^行設(shè)置了灰色背景和粗體字,數(shù)據(jù)行居中對齊,并實現(xiàn)了隔行變色效果,使表格更加清晰易讀。
3. 設(shè)置表格樣式與邊框
為了讓表格更具專業(yè)性和可讀性,我們可以應(yīng)用預(yù)設(shè)的表格樣式并自定義邊框樣式:
from spire.doc import *
from spire.doc.common import *
# 創(chuàng)建文檔
document = Document()
section = document.AddSection()
# 添加標題
title = section.AddParagraph()
text_Range = title.AppendText("季度銷售報表")
title.Format.HorizontalAlignment = HorizontalAlignment.Center
text_Range.CharacterFormat.Bold = True
text_Range.CharacterFormat.FontSize = 18
section.AddParagraph()
# 創(chuàng)建表格
table = section.AddTable(True)
table.ResetCells(5, 4)
# 填充表頭
headers = ["產(chǎn)品名稱", "第一季度", "第二季度", "第三季度"]
for i, header in enumerate(headers):
cell = table.Rows[0].Cells[i]
cell.AddParagraph().AppendText(header)
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
# 填充數(shù)據(jù)
data = [
["筆記本電腦", "120萬", "135萬", "150萬"],
["平板電腦", "85萬", "92萬", "105萬"],
["智能手機", "200萬", "220萬", "245萬"],
["智能手表", "45萬", "52萬", "60萬"],
]
for row_idx, row_data in enumerate(data):
for col_idx, value in enumerate(row_data):
table.Rows[row_idx + 1].Cells[col_idx].AddParagraph().AppendText(value)
# 應(yīng)用表格樣式
table.ApplyStyle(DefaultTableStyle.ColorfulListAccent1)
# 自定義邊框樣式
table.Format.Borders.BorderType = BorderStyle.Single
table.Format.Borders.LineWidth = 1.0
table.Format.Borders.Color = Color.get_Black()
# 設(shè)置外邊框加粗
table.Format.Borders.Left.LineWidth = 2.0
table.Format.Borders.Right.LineWidth = 2.0
table.Format.Borders.Top.LineWidth = 2.0
table.Format.Borders.Bottom.LineWidth = 2.0
# 保存文檔
document.SaveToFile("SalesReport.docx", FileFormat.Docx)
document.Close()
print("銷售報表已創(chuàng)建完成")文檔預(yù)覽:

說明:ApplyStyle() 方法應(yīng)用預(yù)設(shè)的表格樣式,Format.Borders 屬性用于設(shè)置邊框樣式。我們可以單獨設(shè)置上下左右邊框的寬度、顏色和類型,創(chuàng)建專業(yè)的表格外觀。
4. 合并與拆分單元格:創(chuàng)建復(fù)雜表格結(jié)構(gòu)
在實際業(yè)務(wù)中,我們經(jīng)常需要創(chuàng)建包含合并單元格的復(fù)雜表格結(jié)構(gòu),例如產(chǎn)品規(guī)格對比表:
from spire.doc import *
from spire.doc.common import *
# 創(chuàng)建文檔
document = Document()
section = document.AddSection()
# 添加標題
title = section.AddParagraph()
text_range = title.AppendText("產(chǎn)品規(guī)格對比表")
title.Format.HorizontalAlignment = HorizontalAlignment.Center
text_range.CharacterFormat.Bold = True
text_range.CharacterFormat.FontSize = 18
section.AddParagraph()
# 創(chuàng)建表格(8行6列)
table = section.AddTable(True)
table.ResetCells(8, 6)
# 填充表頭(合并第一行的前3列和后3列)
table.ApplyHorizontalMerge(0, 0, 2) # 合并第1行的第1-3列
table.ApplyHorizontalMerge(0, 3, 5) # 合并第1行的第4-6列
table.Rows[0].Cells[0].AddParagraph().AppendText("基礎(chǔ)信息")
table.Rows[0].Cells[3].AddParagraph().AppendText("技術(shù)參數(shù)")
# 填充第二列表頭
sub_headers = ["產(chǎn)品名稱", "型號", "價格", "處理器", "內(nèi)存", "存儲"]
for i, header in enumerate(sub_headers):
table.Rows[1].Cells[i].AddParagraph().AppendText(header)
# 填充產(chǎn)品數(shù)據(jù)
products = [
["ProBook X1", "PB-2024", "5999元", "i7-1360P", "16GB", "512GB SSD"],
["UltraBook Pro", "UB-2024", "7999元", "i7-1370P", "32GB", "1TB SSD"],
["Gaming Laptop", "GL-2024", "9999元", "i9-13900HX", "32GB", "1TB SSD"],
]
for row_idx, product in enumerate(products):
for col_idx, value in enumerate(product):
table.Rows[row_idx + 2].Cells[col_idx].AddParagraph().AppendText(value)
# 合并底部的備注行(合并所有列)
note_row = table.Rows[6]
table.ApplyHorizontalMerge(6, 0, 5)
note_row.Cells[0].AddParagraph().AppendText("注:以上價格僅供參考,實際價格以官網(wǎng)為準。")
# 在最后一行拆分單元格
table.Rows[7].Cells[0].SplitCell(3, 2) # 將第8行第1列拆分為3行2列
# 保存文檔
document.SaveToFile("ProductComparison.docx", FileFormat.Docx)
document.Close()
print("產(chǎn)品規(guī)格對比表已創(chuàng)建完成")文檔預(yù)覽:

說明:ApplyHorizontalMerge() 方法用于水平合并單元格(同一行內(nèi)),ApplyVerticalMerge() 方法用于垂直合并單元格(同一列內(nèi))。SplitCell() 方法可以將一個單元格拆分為多個單元格,實現(xiàn)更靈活的表格布局。
5. 創(chuàng)建嵌套表格:展示層級數(shù)據(jù)
嵌套表格可以在一個單元格內(nèi)包含另一個表格,適用于展示具有層級關(guān)系的數(shù)據(jù),例如產(chǎn)品目錄:
from spire.doc import *
from spire.doc.common import *
# 創(chuàng)建文檔
document = Document()
section = document.AddSection()
# 添加標題
title = section.AddParagraph()
text_range = title.AppendText("產(chǎn)品目錄")
title.Format.HorizontalAlignment = HorizontalAlignment.Center
text_range.CharacterFormat.Bold = True
text_range.CharacterFormat.FontSize = 18
section.AddParagraph()
# 創(chuàng)建主表格(3行2列)
main_table = section.AddTable(True)
main_table.ResetCells(3, 2)
# 設(shè)置主表格列寬
main_table.Rows[0].Cells[0].SetCellWidth(150, CellWidthType.Point)
main_table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)
# 填充主表格第一列(產(chǎn)品類別)
main_table.Rows[0].Cells[0].AddParagraph().AppendText("電子產(chǎn)品")
main_table.Rows[1].Cells[0].AddParagraph().AppendText("家居用品")
main_table.Rows[2].Cells[0].AddParagraph().AppendText("辦公用品")
# 在第一行第二列創(chuàng)建嵌套表格(電子產(chǎn)品)
nested_table1 = main_table.Rows[0].Cells[1].AddTable(True)
nested_table1.ResetCells(4, 3)
nested_table1.AutoFit(AutoFitBehaviorType.AutoFitToContents)
# 填充嵌套表格1的表頭
nested_headers = ["產(chǎn)品名稱", "型號", "價格"]
for i, header in enumerate(nested_headers):
cell = nested_table1.Rows[0].Cells[i]
cell.CellFormat.Shading.BackgroundPatternColor = Color.get_LightGray()
cell.AddParagraph().AppendText(header)
# 填充嵌套表格1的數(shù)據(jù)
electronics = [
["智能手機", "SP-2024", "3999元"],
["平板電腦", "TB-2024", "2999元"],
["智能手表", "SW-2024", "1999元"],
]
for row_idx, item in enumerate(electronics):
for col_idx, value in enumerate(item):
nested_table1.Rows[row_idx + 1].Cells[col_idx].AddParagraph().AppendText(value)
# 在第二行第二列創(chuàng)建嵌套表格(家居用品)
nested_table2 = main_table.Rows[1].Cells[1].AddTable(True)
nested_table2.ResetCells(3, 3)
nested_table2.AutoFit(AutoFitBehaviorType.AutoFitToContents)
for i, header in enumerate(nested_headers):
cell = nested_table2.Rows[0].Cells[i]
cell.CellFormat.Shading.BackgroundPatternColor = Color.get_LightGray()
cell.AddParagraph().AppendText(header)
home_goods = [
["電飯煲", "RC-2024", "599元"],
["空氣凈化器", "AP-2024", "1299元"],
]
for row_idx, item in enumerate(home_goods):
for col_idx, value in enumerate(item):
nested_table2.Rows[row_idx + 1].Cells[col_idx].AddParagraph().AppendText(value)
# 在第三行第二列創(chuàng)建嵌套表格(辦公用品)
nested_table3 = main_table.Rows[2].Cells[1].AddTable(True)
nested_table3.ResetCells(3, 3)
nested_table3.AutoFit(AutoFitBehaviorType.AutoFitToContents)
for i, header in enumerate(nested_headers):
cell = nested_table3.Rows[0].Cells[i]
cell.CellFormat.Shading.BackgroundPatternColor = Color.get_LightGray()
cell.AddParagraph().AppendText(header)
office_supplies = [
["打印機", "PR-2024", "1599元"],
["碎紙機", "SH-2024", "399元"],
]
for row_idx, item in enumerate(office_supplies):
for col_idx, value in enumerate(item):
nested_table3.Rows[row_idx + 1].Cells[col_idx].AddParagraph().AppendText(value)
# 保存文檔
document.SaveToFile("ProductCatalog.docx", FileFormat.Docx)
document.Close()
print("產(chǎn)品目錄已創(chuàng)建完成")文檔預(yù)覽:

說明:
通過 cell.AddTable(True) 方法在單元格內(nèi)創(chuàng)建嵌套表格。每個嵌套表格可以獨立設(shè)置行數(shù)、列數(shù)和樣式,非常適合展示具有層級關(guān)系的數(shù)據(jù),如產(chǎn)品分類、部門組織結(jié)構(gòu)等。
6. 技術(shù)細節(jié)總結(jié)與關(guān)鍵類方法概覽
在前面的章節(jié)中,我們展示了如何使用 Free Spire.Doc for Python 創(chuàng)建基礎(chǔ)表格、設(shè)置表格樣式、合并與拆分單元格以及創(chuàng)建嵌套表格。從技術(shù)實現(xiàn)角度來看,Word 表格操作的核心流程可以總結(jié)為以下幾個關(guān)鍵步驟:
Python Word 表格操作步驟總結(jié)
- 創(chuàng)建文檔對象使用
Document()創(chuàng)建 Word 文檔對象,通過AddSection()添加節(jié),為表格提供容器。 - 創(chuàng)建表格使用
section.AddTable(True)創(chuàng)建表格,通過ResetCells()設(shè)置表格的行數(shù)和列數(shù)。 - 填充表格內(nèi)容通過
table.Rows[row_index].Cells[col_index]訪問單元格,使用AddParagraph().AppendText()方法添加文本內(nèi)容。 - 設(shè)置單元格格式使用
CellFormat屬性設(shè)置單元格的背景顏色、垂直對齊方式、邊框等樣式。 - 合并與拆分單元格使用
ApplyHorizontalMerge()和ApplyVerticalMerge()方法合并單元格,使用SplitCell()方法拆分單元格。 - 應(yīng)用表格樣式使用
ApplyStyle()應(yīng)用預(yù)設(shè)的表格樣式,或通過Format.Borders自定義邊框樣式。 - 保存文檔使用
SaveToFile()方法將文檔保存到指定路徑。
關(guān)鍵類、方法與屬性
| 類 / 方法 / 屬性 | 說明 |
|---|---|
Document | Word 文檔對象,支持創(chuàng)建、加載和保存文檔 |
Document.SaveToFile() | 將文檔保存到指定文件路徑 |
Section | 表示文檔中的節(jié),是表格的容器對象 |
Table | 表示表格對象,包含行和單元格 |
Paragraph | 表示段落對象 |
TextRange.CharacterFormat | 獲取文本格式對象,用于設(shè)置字體、大小、加粗等 |
通過理解上述關(guān)鍵類、方法和屬性,你可以靈活地創(chuàng)建各種類型的 Word 表格,并根據(jù)業(yè)務(wù)需求進行精細定制。掌握這些技術(shù)細節(jié),能讓你在實際項目中快速生成高質(zhì)量、格式統(tǒng)一的 Word 文檔報表,同時保持代碼簡潔和可維護性。
總結(jié)
本文以實際業(yè)務(wù)場景為例,展示了如何使用 Free Spire.Doc for Python 在 Word 文檔中創(chuàng)建基礎(chǔ)表格、設(shè)置表格樣式、合并與拆分單元格、創(chuàng)建嵌套表格等實用功能。通過編程方式生成表格,不僅避免了手動操作的繁瑣和易錯問題,還能輕松應(yīng)對批量報告和復(fù)雜數(shù)據(jù)呈現(xiàn)需求。
掌握這一技能后,你可以將文檔生成與數(shù)據(jù)管理完全自動化,從而節(jié)省時間,提高效率,并為業(yè)務(wù)流程提供可靠的文檔支持。結(jié)合 Free Spire.Doc 的其他功能,如文檔模板、郵件合并、圖表插入等,可以進一步打造智能化的 Word 文檔自動化工作流,讓企業(yè)的文檔處理能力提升到新的高度。
以上就是使用Python在Word文檔中創(chuàng)建表格并設(shè)置各種格式的詳細內(nèi)容,更多關(guān)于Python Word創(chuàng)建表格并設(shè)置格式的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
完美處理python與anaconda環(huán)境變量的沖突問題
這篇文章主要介紹了完美處理Python與anaconda環(huán)境變量的沖突問題,對anaconda感興趣的同學(xué),可以參考下2021-04-04
Pandas庫之DataFrame使用的學(xué)習(xí)筆記
這篇文章主要介紹了Pandas庫之DataFrame使用的學(xué)習(xí)筆記,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
使用50行Python代碼從零開始實現(xiàn)一個AI平衡小游戲
本文會為大家展示機器學(xué)習(xí)專家 Mike Shi 如何用 50 行 Python 代碼創(chuàng)建一個 AI,使用增強學(xué)習(xí)技術(shù),玩耍一個保持桿子平衡的小游戲。本文給大家?guī)韺崿F(xiàn)思路及簡單代碼,感興趣的朋友跟隨小編一起看看吧2018-11-11
Python3 main函數(shù)使用sys.argv傳入多個參數(shù)的實現(xiàn)
今天小編就為大家分享一篇Python3 main函數(shù)使用sys.argv傳入多個參數(shù)的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
詳解Python如何利用Shelve進行數(shù)據(jù)存儲
Shelve是Python標準庫中的一個模塊,用于實現(xiàn)簡單的數(shù)據(jù)持久化,本文將詳細介紹Shelve模塊的功能和用法,并提供豐富的示例代碼,希望對大家有所幫助2023-11-11
opencv導(dǎo)入頭文件時報錯#include的解決方法
這篇文章主要介紹了opencv導(dǎo)入頭文件時報錯#include的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
pip安裝報錯ModuleNotFoundError的問題解決方法
在使用Python開發(fā)時,經(jīng)常會遇到由于庫安裝失敗導(dǎo)致的錯誤信息,一個常見的錯誤是ModuleNotFoundError: No module named 'cv2',下面我們來看看具體的解決方法吧2025-06-06

