最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Python在Word文檔中創(chuàng)建表格并設置各種格式

 更新時間:2026年03月16日 08:53:02   作者:大丸子  
在現代辦公環(huán)境中,Word 文檔是信息傳遞和報告輸出的重要載體,本文將使用?Free Spire.Doc for Python?展示如何在 Word 文檔中創(chuàng)建基礎表格、設置表格樣式、合并與拆分單元格、創(chuàng)建嵌套表格等實用功能,需要的朋友可以參考下

在現代辦公環(huán)境中,Word 文檔是信息傳遞和報告輸出的重要載體。從制作財務報表、項目進度表,到創(chuàng)建產品對比清單、員工信息表,表格以其清晰的結構化展示能力,成為各類文檔中不可或缺的元素。然而,當需要處理大量數據或定期生成標準化報告時,手動在 Word 中創(chuàng)建和格式化表格不僅耗時耗力,還容易出現格式不一致、數據錄入錯誤等問題。而 Python 憑借其強大的自動化處理能力,結合專業(yè)的文檔操作庫,可以高效地實現 Word 表格的批量創(chuàng)建、格式化和數據填充,大幅提升工作效率。

本文將使用 Free Spire.Doc for Python 展示如何在 Word 文檔中創(chuàng)建基礎表格、設置表格樣式、合并與拆分單元格、創(chuàng)建嵌套表格等實用功能,結合實際業(yè)務場景的數據示例,幫助你快速掌握 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)建基礎表格:員工信息管理

假設我們需要為人力資源部門創(chuàng)建一份員工信息表,包含姓名、部門、職位、入職日期和聯系方式等字段。我們可以在代碼中直接生成表格并填充數據:

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()  # 添加空行
# 準備表頭和數據
headers = ["姓名", "部門", "職位", "入職日期", "聯系方式"]
employees = [
    ["張三", "技術部", "軟件工程師", "2020-03-15", "13800138001"],
    ["李四", "市場部", "市場經理", "2019-06-20", "13800138002"],
    ["王五", "人力資源部", "人力資源專員", "2021-01-10", "13800138003"],
    ["趙六", "財務部", "會計", "2018-11-05", "13800138004"],
    ["錢七", "技術部", "產品經理", "2020-08-22", "13800138005"],
]
# 創(chuàng)建表格
table = section.AddTable(True)
table.ResetCells(len(employees) + 1, len(headers))
# 設置表頭行
header_row = table.Rows[0]
header_row.IsHeader = True
header_row.Height = 30
header_row.HeightType = TableRowHeightType.Exactly
# 填充表頭并設置樣式
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
# 填充數據行
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)
# 設置隔行變色
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)建完成")

文檔預覽:

說明
通過 section.AddTable(True) 創(chuàng)建表格,ResetCells() 方法設置表格的行數和列數。我們?yōu)楸眍^行設置了灰色背景和粗體字,數據行居中對齊,并實現了隔行變色效果,使表格更加清晰易讀。

3. 設置表格樣式與邊框

為了讓表格更具專業(yè)性和可讀性,我們可以應用預設的表格樣式并自定義邊框樣式:

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 = ["產品名稱", "第一季度", "第二季度", "第三季度"]
for i, header in enumerate(headers):
    cell = table.Rows[0].Cells[i]
    cell.AddParagraph().AppendText(header)
    cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
# 填充數據
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)
# 應用表格樣式
table.ApplyStyle(DefaultTableStyle.ColorfulListAccent1)
# 自定義邊框樣式
table.Format.Borders.BorderType = BorderStyle.Single
table.Format.Borders.LineWidth = 1.0
table.Format.Borders.Color = Color.get_Black()
# 設置外邊框加粗
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)建完成")

文檔預覽:

說明
ApplyStyle() 方法應用預設的表格樣式,Format.Borders 屬性用于設置邊框樣式。我們可以單獨設置上下左右邊框的寬度、顏色和類型,創(chuàng)建專業(yè)的表格外觀。

4. 合并與拆分單元格:創(chuàng)建復雜表格結構

在實際業(yè)務中,我們經常需要創(chuàng)建包含合并單元格的復雜表格結構,例如產品規(guī)格對比表:

from spire.doc import *
from spire.doc.common import *
# 創(chuàng)建文檔
document = Document()
section = document.AddSection()
# 添加標題
title = section.AddParagraph()
text_range = title.AppendText("產品規(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("基礎信息")
table.Rows[0].Cells[3].AddParagraph().AppendText("技術參數")
# 填充第二列表頭
sub_headers = ["產品名稱", "型號", "價格", "處理器", "內存", "存儲"]
for i, header in enumerate(sub_headers):
    table.Rows[1].Cells[i].AddParagraph().AppendText(header)
# 填充產品數據
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("注:以上價格僅供參考,實際價格以官網為準。")
# 在最后一行拆分單元格
table.Rows[7].Cells[0].SplitCell(3, 2)  # 將第8行第1列拆分為3行2列
# 保存文檔
document.SaveToFile("ProductComparison.docx", FileFormat.Docx)
document.Close()
print("產品規(guī)格對比表已創(chuàng)建完成")

文檔預覽:

說明
ApplyHorizontalMerge() 方法用于水平合并單元格(同一行內),ApplyVerticalMerge() 方法用于垂直合并單元格(同一列內)。SplitCell() 方法可以將一個單元格拆分為多個單元格,實現更靈活的表格布局。

5. 創(chuàng)建嵌套表格:展示層級數據

嵌套表格可以在一個單元格內包含另一個表格,適用于展示具有層級關系的數據,例如產品目錄:

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)建主表格(3行2列)
main_table = section.AddTable(True)
main_table.ResetCells(3, 2)
# 設置主表格列寬
main_table.Rows[0].Cells[0].SetCellWidth(150, CellWidthType.Point)
main_table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)
# 填充主表格第一列(產品類別)
main_table.Rows[0].Cells[0].AddParagraph().AppendText("電子產品")
main_table.Rows[1].Cells[0].AddParagraph().AppendText("家居用品")
main_table.Rows[2].Cells[0].AddParagraph().AppendText("辦公用品")
# 在第一行第二列創(chuàng)建嵌套表格(電子產品)
nested_table1 = main_table.Rows[0].Cells[1].AddTable(True)
nested_table1.ResetCells(4, 3)
nested_table1.AutoFit(AutoFitBehaviorType.AutoFitToContents)
# 填充嵌套表格1的表頭
nested_headers = ["產品名稱", "型號", "價格"]
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的數據
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("產品目錄已創(chuàng)建完成")

文檔預覽:

說明
通過 cell.AddTable(True) 方法在單元格內創(chuàng)建嵌套表格。每個嵌套表格可以獨立設置行數、列數和樣式,非常適合展示具有層級關系的數據,如產品分類、部門組織結構等。

6. 技術細節(jié)總結與關鍵類方法概覽

在前面的章節(jié)中,我們展示了如何使用 Free Spire.Doc for Python 創(chuàng)建基礎表格、設置表格樣式、合并與拆分單元格以及創(chuàng)建嵌套表格。從技術實現角度來看,Word 表格操作的核心流程可以總結為以下幾個關鍵步驟:

Python Word 表格操作步驟總結

  • 創(chuàng)建文檔對象使用 Document() 創(chuàng)建 Word 文檔對象,通過 AddSection() 添加節(jié),為表格提供容器。
  • 創(chuàng)建表格使用 section.AddTable(True) 創(chuàng)建表格,通過 ResetCells() 設置表格的行數和列數。
  • 填充表格內容通過 table.Rows[row_index].Cells[col_index] 訪問單元格,使用 AddParagraph().AppendText() 方法添加文本內容。
  • 設置單元格格式使用 CellFormat 屬性設置單元格的背景顏色、垂直對齊方式、邊框等樣式。
  • 合并與拆分單元格使用 ApplyHorizontalMerge() 和 ApplyVerticalMerge() 方法合并單元格,使用 SplitCell() 方法拆分單元格。
  • 應用表格樣式使用 ApplyStyle() 應用預設的表格樣式,或通過 Format.Borders 自定義邊框樣式。
  • 保存文檔使用 SaveToFile() 方法將文檔保存到指定路徑。

關鍵類、方法與屬性

類 / 方法 / 屬性說明
DocumentWord 文檔對象,支持創(chuàng)建、加載和保存文檔
Document.SaveToFile()將文檔保存到指定文件路徑
Section表示文檔中的節(jié),是表格的容器對象
Table表示表格對象,包含行和單元格
Paragraph表示段落對象
TextRange.CharacterFormat獲取文本格式對象,用于設置字體、大小、加粗等

通過理解上述關鍵類、方法和屬性,你可以靈活地創(chuàng)建各種類型的 Word 表格,并根據業(yè)務需求進行精細定制。掌握這些技術細節(jié),能讓你在實際項目中快速生成高質量、格式統(tǒng)一的 Word 文檔報表,同時保持代碼簡潔和可維護性。

總結

本文以實際業(yè)務場景為例,展示了如何使用 Free Spire.Doc for Python 在 Word 文檔中創(chuàng)建基礎表格、設置表格樣式、合并與拆分單元格、創(chuàng)建嵌套表格等實用功能。通過編程方式生成表格,不僅避免了手動操作的繁瑣和易錯問題,還能輕松應對批量報告和復雜數據呈現需求。

掌握這一技能后,你可以將文檔生成與數據管理完全自動化,從而節(jié)省時間,提高效率,并為業(yè)務流程提供可靠的文檔支持。結合 Free Spire.Doc 的其他功能,如文檔模板、郵件合并、圖表插入等,可以進一步打造智能化的 Word 文檔自動化工作流,讓企業(yè)的文檔處理能力提升到新的高度。

以上就是使用Python在Word文檔中創(chuàng)建表格并設置各種格式的詳細內容,更多關于Python Word創(chuàng)建表格并設置格式的資料請關注腳本之家其它相關文章!

相關文章

  • 完美處理python與anaconda環(huán)境變量的沖突問題

    完美處理python與anaconda環(huán)境變量的沖突問題

    這篇文章主要介紹了完美處理Python與anaconda環(huán)境變量的沖突問題,對anaconda感興趣的同學,可以參考下
    2021-04-04
  • Pandas庫之DataFrame使用的學習筆記

    Pandas庫之DataFrame使用的學習筆記

    這篇文章主要介紹了Pandas庫之DataFrame使用的學習筆記,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-06-06
  • 使用50行Python代碼從零開始實現一個AI平衡小游戲

    使用50行Python代碼從零開始實現一個AI平衡小游戲

    本文會為大家展示機器學習專家 Mike Shi 如何用 50 行 Python 代碼創(chuàng)建一個 AI,使用增強學習技術,玩耍一個保持桿子平衡的小游戲。本文給大家?guī)韺崿F思路及簡單代碼,感興趣的朋友跟隨小編一起看看吧
    2018-11-11
  • Python3 main函數使用sys.argv傳入多個參數的實現

    Python3 main函數使用sys.argv傳入多個參數的實現

    今天小編就為大家分享一篇Python3 main函數使用sys.argv傳入多個參數的實現,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • 深入了解PyQt5中的圖形視圖框架

    深入了解PyQt5中的圖形視圖框架

    PyQt5中圖形視圖框架主要包含三個類:QGraphicsItem圖元類、QGraphicsScene場景類和QGraphicsView視圖類。本文將通過示例詳細講解一下這三個類,感興趣的可以學習一下
    2022-03-03
  • 詳解Python如何利用Shelve進行數據存儲

    詳解Python如何利用Shelve進行數據存儲

    Shelve是Python標準庫中的一個模塊,用于實現簡單的數據持久化,本文將詳細介紹Shelve模塊的功能和用法,并提供豐富的示例代碼,希望對大家有所幫助
    2023-11-11
  • opencv導入頭文件時報錯#include的解決方法

    opencv導入頭文件時報錯#include的解決方法

    這篇文章主要介紹了opencv導入頭文件時報錯#include的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-07-07
  • Python辦公自動化之openpyxl使用與避坑全面指南

    Python辦公自動化之openpyxl使用與避坑全面指南

    在現代職場中,Excel 無疑是數據處理的霸主, Python 的 openpyxl 庫可以幫你自動處理 Excel 表格,下面小編將帶你從零開始,系統(tǒng)掌握使用 Python 讀寫,修改和格式化 Excel 文件的核心技能
    2026-01-01
  • pip安裝報錯ModuleNotFoundError的問題解決方法

    pip安裝報錯ModuleNotFoundError的問題解決方法

    在使用Python開發(fā)時,經常會遇到由于庫安裝失敗導致的錯誤信息,一個常見的錯誤是ModuleNotFoundError: No module named 'cv2',下面我們來看看具體的解決方法吧
    2025-06-06
  • 全面剖析Python的Django框架中的項目部署技巧

    全面剖析Python的Django框架中的項目部署技巧

    這篇文章主要全面剖析了Python的Django框架的部署技巧,包括Fabric等自動化部署和建立單元測試等方面,強烈推薦!需要的朋友可以參考下
    2015-04-04

最新評論

镇赉县| 常熟市| 建阳市| 桐乡市| 阳泉市| 称多县| 开阳县| 石狮市| 新邵县| 台中县| 沙洋县| 甘肃省| 临沂市| 云安县| 徐州市| 黎川县| 建瓯市| 丹寨县| 安西县| 子长县| 潜江市| 郓城县| 远安县| 璧山县| 绥德县| 望城县| 临沂市| 普兰店市| 南康市| 杨浦区| 交口县| 香格里拉县| 新丰县| 萝北县| 富平县| 连江县| 墨竹工卡县| 蓬莱市| 乐都县| 慈溪市| 崇阳县|