Python使用Free Spire.Doc for Python實現(xiàn)自動化生成Word文檔
在自動化辦公場景中,批量生成合同、分析報告或項目說明書是常見需求。如果仍依賴手動復(fù)制粘貼,不僅效率低下,格式統(tǒng)一與結(jié)構(gòu)規(guī)范也難以保證。本文將介紹如何使用免費庫 Free Spire.Doc for Python 以編程方式生成 Word 文檔,涵蓋從基礎(chǔ)文檔創(chuàng)建到表格、圖片等豐富內(nèi)容的綜合示例。
環(huán)境準(zhǔn)備
Free Spire.Doc for Python 是一個用于處理 Word 文檔的 Python 庫,支持在不依賴 Microsoft Word 環(huán)境的情況下創(chuàng)建、讀取、修改和轉(zhuǎn)換 Word 文檔(包括 .doc 和 .docx 格式)。
使用 pip 即可完成安裝:
pip install Spire.Doc.Free
注意:免費版面存在固定容量限制:單文檔最大支持 500 個段落、25 張數(shù)據(jù)表,超出限額內(nèi)容會被自動截斷。該限制基本可以滿足日常報表、測試文檔、小型臺賬的自動化生成需求,大批量超長篇文檔需更換其他方案選型。
安裝完成后,在 Python 腳本中導(dǎo)入所需模塊:
from spire.doc import * from spire.doc.common import *
基礎(chǔ)示例:使用 Python 創(chuàng)建 Word 文檔
1. 基礎(chǔ)文檔結(jié)構(gòu)
Word 文檔的組織層次如下:
Document → Section → Paragraph → TextRange。
Document 是整個文檔的根對象;每個 Document 至少包含一個 Section;Section 是頁面布局的基本單位,可以獨立設(shè)置頁眉頁腳和頁面屬性;Paragraph 是文本容器;TextRange 則對應(yīng)段落中的一段連續(xù)文本。
以下代碼創(chuàng)建一份基礎(chǔ)的 Word 文檔:
# 創(chuàng)建 Document 對象
doc = Document()
# 添加一節(jié)
section = doc.AddSection()
# 設(shè)置頁面邊距(單位:磅)
section.PageSetup.Margins.Top = 60
section.PageSetup.Margins.Bottom = 60
section.PageSetup.Margins.Left = 70
section.PageSetup.Margins.Right = 70
# 添加標(biāo)題段落
title = section.AddParagraph()
title.AppendText("2026年度技術(shù)報告")
title.ApplyStyle(BuiltinStyle.Title)
# 添加一級標(biāo)題
heading1 = section.AddParagraph()
heading1.AppendText("一、項目概況")
heading1.ApplyStyle(BuiltinStyle.Heading1)
# 添加正文段落
para = section.AddParagraph()
para.AppendText("本報告總結(jié)了2026年度技術(shù)團(tuán)隊在核心產(chǎn)品研發(fā)、性能優(yōu)化和用戶體驗提升等方面的工作成果。")
para.ApplyStyle(BuiltinStyle.Normal)
# 保存文檔
doc.SaveToFile("demo.docx")
doc.Dispose()
2. 自定義字體和段落樣式
除了使用 Word 內(nèi)置樣式(如 Title、Heading1 等),還可以創(chuàng)建自定義樣式:
# 創(chuàng)建自定義段落樣式
custom_style = ParagraphStyle(doc)
custom_style.Name = "CustomStyle"
custom_style.CharacterFormat.FontName = "宋體"
custom_style.CharacterFormat.FontSize = 12
custom_style.CharacterFormat.Bold = False
custom_style.CharacterFormat.TextColor = Color.get_Gray()
doc.Styles.Add(custom_style)
# 應(yīng)用到段落
para.ApplyStyle("CustomStyle")
段落對齊方式可以通過 Format 屬性設(shè)置:
title.Format.HorizontalAlignment = HorizontalAlignment.Center para.Format.HorizontalAlignment = HorizontalAlignment.Left
進(jìn)階場景 1:動態(tài)插入業(yè)務(wù)數(shù)據(jù)表格
自動化報表最常用場景:讀取結(jié)構(gòu)化數(shù)據(jù)并寫入 Word 表格,支持自適應(yīng)頁面寬度、內(nèi)置表格樣式,示例寫入簡易銷售臺賬數(shù)據(jù):
from spire.doc import *
from spire.doc.common import *
doc = Document()
section = doc.AddSection()
section.PageSetup.Margins.All = 40
# 表頭數(shù)據(jù)與業(yè)務(wù)明細(xì)數(shù)據(jù)
header = ["月份", "產(chǎn)品線", "營收金額(元)", "同比增幅"]
data_list = [
["1月", "軟件服務(wù)", "235000", "6.2%"],
["2月", "硬件產(chǎn)品", "189000", "-2.1%"],
["3月", "運維外包", "321000", "12.5%"]
]
# 創(chuàng)建4列4行表格
table = section.AddTable()
table.ResetCells(len(data_list)+1, len(header))
# 表格自動適配頁面寬度
table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)
# 套用內(nèi)置淺色表格樣式
table.ApplyStyle(DefaultTableStyle.GridTable1LightAccent6)
# 填充表頭
for col_idx, val in enumerate(header):
cell = table.Rows[0].Cells[col_idx]
cell.AddParagraph().AppendText(val).CharacterFormat.Bold = True
# 填充明細(xì)數(shù)據(jù)
for row_idx, row_data in enumerate(data_list, start=1):
for col_idx, val in enumerate(row_data):
table.Rows[row_idx].Cells[col_idx].AddParagraph().AppendText(val)
doc.SaveToFile("業(yè)務(wù)數(shù)據(jù)表.docx", FileFormat.Docx)
doc.Dispose()
進(jìn)階場景 2:插入圖片
使用 Paragraph.AppendPicture() 方法可以將圖片插入到 Word 文檔的段落中。下面是一個在正文中插入產(chǎn)品圖片的示例:
from spire.doc import *
from spire.doc.common import *
doc = Document()
section = doc.AddSection()
# 添加標(biāo)題
title = section.AddParagraph()
title.AppendText("產(chǎn)品示意圖")
title.ApplyStyle(BuiltinStyle.Heading1)
# 添加用于說明的正文
caption = section.AddParagraph()
caption.AppendText("下圖展示了產(chǎn)品結(jié)構(gòu)示意圖:")
# 插入圖片
image_para = section.AddParagraph()
picture = image_para.AppendPicture("product_diagram.png")
# 設(shè)置圖片尺寸(單位:點)
picture.Width = 400
picture.Height = 300
# 設(shè)置圖片居中對齊
image_para.Format.HorizontalAlignment = HorizontalAlignment.Center
# 添加圖片下方的說明文字
caption_below = section.AddParagraph()
caption_below.AppendText("圖1 產(chǎn)品結(jié)構(gòu)示意圖")
caption_below.Format.HorizontalAlignment = HorizontalAlignment.Center
doc.SaveToFile("report_with_image.docx")
doc.Dispose()
進(jìn)階場景 3:添加頁眉和頁腳
頁眉和頁腳屬于 Section 級別的組件,需要添加到 Section 對應(yīng)的 HeadersFooters 屬性中:
from spire.doc import *
from spire.doc.common import *
doc = Document()
section = doc.AddSection()
# 設(shè)置頁面方向(橫向或縱向)
section.PageSetup.Orientation = PageOrientation.Portrait
# 添加頁眉
header = section.HeadersFooters.Header.AddParagraph()
header.AppendText("公司內(nèi)部資料 - 技術(shù)報告")
header.Format.HorizontalAlignment = HorizontalAlignment.Right
# 添加頁腳并插入頁碼
footer = section.HeadersFooters.Footer.AddParagraph()
footer.AppendField("Page", FieldType.FieldPage)
footer.AppendText(" / ")
footer.AppendField("NumPages", FieldType.FieldNumPages)
footer.Format.HorizontalAlignment = HorizontalAlignment.Center
# 添加正文內(nèi)容
content = section.AddParagraph()
content.AppendText("報告正文內(nèi)容...")
doc.SaveToFile("帶頁眉頁腳.docx")
doc.Dispose()
綜合示例:自動生成項目報告文檔
以下綜合示例整合了前文介紹的各項功能,演示如何自動生成一份完整的項目結(jié)項報告文檔:
from spire.doc import *
from spire.doc.common import *
def generate_project_report(project_name, start_date, end_date, budget, metrics, summary):
"""
生成項目結(jié)項報告文檔
參數(shù):
project_name: 項目名稱
start_date: 開始日期
end_date: 結(jié)束日期
budget: 項目預(yù)算(萬元)
metrics: 關(guān)鍵指標(biāo)列表,每個元素為(指標(biāo)名稱, 實際值, 目標(biāo)值)
summary: 項目總結(jié)文本
"""
doc = Document()
section = doc.AddSection()
# 頁面設(shè)置
section.PageSetup.Margins.Top = 70
section.PageSetup.Margins.Bottom = 70
section.PageSetup.Margins.Left = 60
section.PageSetup.Margins.Right = 60
# 頁眉
header = section.HeadersFooters.Header.AddParagraph()
header.AppendText("項目結(jié)項報告 - 內(nèi)部使用")
header.Format.HorizontalAlignment = HorizontalAlignment.Center
# 頁腳(自動頁碼)
footer = section.HeadersFooters.Footer.AddParagraph()
footer.AppendField("Page", FieldType.FieldPage)
footer.AppendText(" / ")
footer.AppendField("NumPages", FieldType.FieldNumPages)
footer.Format.HorizontalAlignment = HorizontalAlignment.Center
# 主標(biāo)題
title = section.AddParagraph()
title.AppendText(f"{project_name} - 結(jié)項報告")
title.ApplyStyle(BuiltinStyle.Title)
title.Format.HorizontalAlignment = HorizontalAlignment.Center
title.Format.AfterSpacing = 20
# 基本信息區(qū)域
heading_basic = section.AddParagraph()
heading_basic.AppendText("一、項目基本信息")
heading_basic.ApplyStyle(BuiltinStyle.Heading1)
info_table = section.AddTable(True)
info_table.ResetCells(4, 2)
info_table.TableFormat.Borders.BorderType = BorderStyle.Single
info_data = [("項目名稱", project_name), ("執(zhí)行周期", f"{start_date} 至 {end_date}"),
("預(yù)算金額", f"{budget} 萬元"), ("報告日期", "2026年6月")]
for i, (key, value) in enumerate(info_data):
info_table.Rows[i].Cells[0].AddParagraph().AppendText(key)
info_table.Rows[i].Cells[1].AddParagraph().AppendText(value)
# 設(shè)置第一列樣式(標(biāo)簽列加粗)
info_table.Rows[i].Cells[0].AddParagraph().ApplyStyle(BuiltinStyle.Normal)
# 關(guān)鍵指標(biāo)表格
heading_metrics = section.AddParagraph()
heading_metrics.AppendText("二、關(guān)鍵指標(biāo)完成情況")
heading_metrics.ApplyStyle(BuiltinStyle.Heading1)
metrics_table = section.AddTable(True)
metrics_table.ResetCells(len(metrics) + 1, 3)
metrics_table.TableFormat.Borders.BorderType = BorderStyle.Single
# 表頭
metric_headers = ["指標(biāo)名稱", "實際值", "目標(biāo)值"]
for idx, header in enumerate(metric_headers):
metrics_table.Rows[0].Cells[idx].AddParagraph().AppendText(header)
metrics_table.Rows[0].Cells[idx].AddParagraph().ApplyStyle(BuiltinStyle.Normal)
# 填充指標(biāo)數(shù)據(jù)
for i, (name, actual, target) in enumerate(metrics):
metrics_table.Rows[i + 1].Cells[0].AddParagraph().AppendText(name)
metrics_table.Rows[i + 1].Cells[1].AddParagraph().AppendText(str(actual))
metrics_table.Rows[i + 1].Cells[2].AddParagraph().AppendText(str(target))
# 項目總結(jié)
heading_summary = section.AddParagraph()
heading_summary.AppendText("三、項目總結(jié)")
heading_summary.ApplyStyle(BuiltinStyle.Heading1)
summary_para = section.AddParagraph()
summary_para.AppendText(summary)
summary_para.ApplyStyle(BuiltinStyle.Normal)
# 保存文檔
output_file = f"{project_name}_結(jié)項報告.docx"
doc.SaveToFile(output_file)
doc.Dispose()
print(f"報告已生成:{output_file}")
# 使用示例
if __name__ == "__main__":
generate_project_report(
project_name="新一代數(shù)據(jù)分析平臺",
start_date="2025-07-01",
end_date="2026-06-30",
budget=280,
metrics=[
("數(shù)據(jù)處理吞吐量(TPS)", 12500, 10000),
("查詢響應(yīng)時間(ms)", 85, 100),
("用戶滿意度評分", 4.8, 4.5),
("功能完成度(%)", 98, 95)
],
summary="本項目成功完成了新一代數(shù)據(jù)分析平臺的研發(fā)和部署工作。各項關(guān)鍵指標(biāo)均達(dá)到或超過預(yù)期目標(biāo),系統(tǒng)上線后運行穩(wěn)定,獲得了用戶的積極反饋。后續(xù)將在二期項目中繼續(xù)推進(jìn)AI分析功能和移動端支持的開發(fā)。"
)
補(bǔ)充拓展:常用衍生能力
- 列表生成:通過
ListFormat.ApplyStyle()快速生成有序 / 無序列表,適配條款、清單類文檔; - 格式轉(zhuǎn)換:支持 MD、HTML 文件直接載入后另存為
docx,實現(xiàn) Markdown 文檔批量轉(zhuǎn) Word; - 文檔編輯:可加載已有
docx文件,檢索替換指定關(guān)鍵詞、追加新段落,實現(xiàn)文檔二次修改。
小結(jié)
以上內(nèi)容演示了一套完整的 Word 文檔生成方案,從創(chuàng)建基礎(chǔ)文檔結(jié)構(gòu)到添加表格、圖片、頁眉頁腳等豐富內(nèi)容,均可通過簡潔的 API 在代碼中實現(xiàn),無需依賴 Microsoft Word 環(huán)境。適用于自動生成報表、批量處理合同文檔、輸出項目報告等開發(fā)任務(wù),滿足日常工作中的文檔自動化處理需求。
到此這篇關(guān)于Python使用Free Spire.Doc for Python實現(xiàn)自動化生成Word文檔的文章就介紹到這了,更多相關(guān)Python生成Word內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
聊聊PyTorch中eval和no_grad的關(guān)系
這篇文章主要介紹了聊聊PyTorch中eval和no_grad的關(guān)系,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05
Python利用heapq實現(xiàn)一個優(yōu)先級隊列的方法
今天小編就為大家分享一篇Python利用heapq實現(xiàn)一個優(yōu)先級隊列的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02
Caffe卷積神經(jīng)網(wǎng)絡(luò)數(shù)據(jù)層及參數(shù)
這篇文章主要為大家介紹了Caffe卷積神經(jīng)網(wǎng)絡(luò)數(shù)據(jù)層及參數(shù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
使用python svm實現(xiàn)直接可用的手寫數(shù)字識別
這篇文章主要介紹了使用python svm實現(xiàn)直接可用的手寫數(shù)字識別,現(xiàn)在網(wǎng)上很多代碼是良莠不齊,真是一言難盡,于是記錄一下,能夠運行成功并識別成功的一個源碼2021-08-08
Python 利用CSV模塊處理數(shù)據(jù)的實現(xiàn)實例
CSV文件的一個主要優(yōu)點是有很多程序可以存儲,轉(zhuǎn)換和處理純文本文件,本文主要介紹了Python 利用CSV模塊處理數(shù)據(jù)的實現(xiàn)實例,具有一定的參考價值,感興趣的可以了解一下2024-03-03

