使用 Python 从零创建 Word 文档

在日常办公自动化场景中,我们经常需要从头开始创建全新的 Word 文档。无论是生成报告、制作表单还是创建标准化模板,掌握如何使用 Python 编程方式构建 Word 文档都能大幅提升工作效率。本文将详细介绍如何使用 Spire.Doc for Python 库从零开始创建结构完整的 Word 文档,包括添加文本、设置格式、插入表格以及添加页眉页脚等核心功能。

环境准备

在开始之前,我们需要安装 Spire.Doc for Python 库。可以通过 pip 命令进行安装:

bash 复制代码
pip install spire.doc

安装完成后,就可以在 Python 代码中导入相关模块并开始创建文档了。

创建最简单的 Word 文档

让我们从最基础的示例开始,创建一个包含简单文本的 Word 文档。这个示例展示了创建文档的基本流程:初始化文档对象、添加节(Section)、添加段落(Paragraph)并追加文本内容。

python 复制代码
from spire.doc.common import *
from spire.doc import *

# 创建 Word 文档对象
document = Document()

# 添加一个新的节
section = document.AddSection()

# 在节中添加一个新段落
paragraph = section.AddParagraph()

# 向段落中追加文本
paragraph.AppendText("你好,世界!")

# 保存为 docx 格式文件
document.SaveToFile("/HelloWorld.docx", FileFormat.Docx)

# 关闭文档对象,释放资源
document.Close()

在这个示例中,我们首先创建了一个 Document 对象作为整个文档的容器。然后通过 AddSection() 方法添加一个节,这是 Word 文档的基本结构单元。接着使用 AddParagraph() 方法在节中添加段落,并通过 AppendText() 方法向段落中写入文本内容。最后调用 SaveToFile() 方法将文档保存到磁盘。

设置页面和添加格式化文本

在实际应用中,我们通常需要更精细地控制文档的布局和文本格式。下面的示例演示了如何设置页面边距、添加标题以及设置文本的字体、大小和颜色等属性。

python 复制代码
from spire.doc import *
from spire.doc.common import *

# 创建文档
doc = Document()
section = doc.AddSection()

# 设置页面大小为 A4
section.PageSetup.PageSize = PageSize.A4()

# 设置页边距(单位:点,1点 = 0.3528毫米)
section.PageSetup.Margins.Top = 72
section.PageSetup.Margins.Bottom = 72
section.PageSetup.Margins.Left = 89.85
section.PageSetup.Margins.Right = 89.85

# 添加标题段落
title = section.AddParagraph()
titleText = title.AppendText("创建您的账户")
titleText.CharacterFormat.FontSize = 18
titleText.CharacterFormat.FontName = "Arial"
titleText.CharacterFormat.TextColor = Color.FromArgb(0xFF, 0x00, 0x71, 0xb6)
title.Format.HorizontalAlignment = HorizontalAlignment.Center
title.Format.AfterSpacing = 8

# 添加描述性文本段落
descriptionStyle = ParagraphStyle(doc)
descriptionStyle.Name = "description"
descriptionStyle.CharacterFormat.FontSize = 12
descriptionStyle.CharacterFormat.FontName = "Arial"
descriptionStyle.CharacterFormat.TextColor = Color.FromArgb(0xFF, 0x00, 0x45, 0x8e)
doc.Styles.Add(descriptionStyle)

p1 = section.AddParagraph()
text1 = "为了验证您的身份并查找您的信息,请提供以下信息。" + \
        "这些信息将用于创建您的在线账户。" + \
        "您的信息不会公开或在此网站上显示。"
p1.AppendText(text1)
p1.ApplyStyle(descriptionStyle.Name)

# 保存文档
doc.SaveToFile("FormattedDocument.docx", FileFormat.Docx)
doc.Close()

在这个示例中,我们首先通过 PageSetup 属性设置了页面的大小和边距。然后创建了一个居中对齐的标题,并设置了其字体大小、名称和颜色。我们还定义了一个自定义的段落样式,并将其应用到描述性文本段落上。这种方式可以确保文档中相同类型的文本保持一致的格式。

在文档中创建表格

表格是 Word 文档中常用的元素,用于组织和展示结构化数据。Spire.Doc 提供了灵活的方式来创建和格式化表格。下面的示例展示了如何直接创建表格并设置单元格的内容和格式。

python 复制代码
from spire.doc import *
from spire.doc.common import *

# 创建 Word 文档
doc = Document()

# 添加一个节
section = doc.AddSection()

# 直接创建表格并设置行数和列数
table = Table(doc)
table.ResetCells(1, 2)

# 设置表格宽度为页面宽度的 100%
table.PreferredWidth = PreferredWidth(WidthType.Percentage, int(100))

# 设置表格边框样式
table.Format.Borders.BorderType = BorderStyle.Single

# 获取第一行并设置高度
row = table.Rows[0]
row.Height = 50.0

# 设置第一个单元格
cell1 = table.Rows[0].Cells[0]
para1 = cell1.AddParagraph()
para1.AppendText("第1行第1列")
para1.Format.HorizontalAlignment = HorizontalAlignment.Center

# 设置单元格背景色和垂直对齐方式
cell1.CellFormat.Shading.BackgroundPatternColor = Color.get_AliceBlue()
cell1.CellFormat.VerticalAlignment = VerticalAlignment.Middle

# 设置第二个单元格
cell2 = table.Rows[0].Cells[1]
para2 = cell2.AddParagraph()
para2.AppendText("第1行第2列")
para2.Format.HorizontalAlignment = HorizontalAlignment.Center
cell2.CellFormat.Shading.BackgroundPatternColor = Color.get_AliceBlue()
cell2.CellFormat.VerticalAlignment = VerticalAlignment.Middle

# 将表格添加到节中
section.Tables.Add(table)

# 保存文档
doc.SaveToFile("/CreateTable.docx", FileFormat.Docx2013)
doc.Close()

在这个示例中,我们通过 Table 类直接创建了一个表格对象,并使用 ResetCells() 方法指定了表格的行数和列数。然后分别对每个单元格进行设置,包括添加文本、设置水平对齐方式、背景颜色和垂直对齐方式。最后将表格添加到节的表格集合中。

添加页眉和页脚

页眉和页脚是专业文档的重要组成部分,通常用于显示文档标题、页码、日期等信息。下面的示例演示了如何在文档中添加包含图片和文本的页眉,以及包含页码的页脚。

python 复制代码
from spire.doc import *
from spire.doc.common import *

def InsertHeaderAndFooter(section):
    """在文档中添加页眉和页脚"""
    # 创建页眉段落并添加图片
    headerParagraph = section.HeadersFooters.Header.AddParagraph()
    headerPicture = headerParagraph.AppendPicture("./Data/Header.png")

    # 添加页眉文本
    text = headerParagraph.AppendText("Spire.Doc 示例")
    text.CharacterFormat.FontName = "Arial"
    text.CharacterFormat.FontSize = 10
    text.CharacterFormat.Italic = True
    headerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right

    # 设置页眉底部边框
    headerParagraph.Format.Borders.Bottom.BorderType = BorderStyle.Single
    headerParagraph.Format.Borders.Bottom.Space = 0.05

    # 设置页眉图片的环绕方式和位置
    headerPicture.TextWrappingStyle = TextWrappingStyle.Behind
    headerPicture.HorizontalOrigin = HorizontalOrigin.Page
    headerPicture.HorizontalAlignment = ShapeHorizontalAlignment.Left
    headerPicture.VerticalOrigin = VerticalOrigin.Page
    headerPicture.VerticalAlignment = ShapeVerticalAlignment.Top

    # 创建页脚段落并添加图片
    footerParagraph = section.HeadersFooters.Footer.AddParagraph()
    footerPicture = footerParagraph.AppendPicture("./Data/Footer.png")

    # 设置页脚图片的位置
    footerPicture.TextWrappingStyle = TextWrappingStyle.Behind
    footerPicture.HorizontalOrigin = HorizontalOrigin.Page
    footerPicture.HorizontalAlignment = ShapeHorizontalAlignment.Left
    footerPicture.VerticalOrigin = VerticalOrigin.Page
    footerPicture.VerticalAlignment = ShapeVerticalAlignment.Bottom

    # 添加页码
    footerParagraph.AppendField("page number", FieldType.FieldPage)
    footerParagraph.AppendText(" / ")
    footerParagraph.AppendField("number of pages", FieldType.FieldNumPages)
    footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right

    # 设置页脚顶部边框
    footerParagraph.Format.Borders.Top.BorderType = BorderStyle.Single
    footerParagraph.Format.Borders.Top.Space = 0.05

# 创建文档
document = Document()
section = document.AddSection()

# 设置页面
section.PageSetup.PageSize = PageSize.A4()
section.PageSetup.Margins.Top = 72
section.PageSetup.Margins.Bottom = 72
section.PageSetup.Margins.Left = 89.85
section.PageSetup.Margins.Right = 89.85

# 添加页眉和页脚
InsertHeaderAndFooter(section)

# 添加标题
title = section.AddParagraph()
titleText = title.AppendText("创建您的账户")
titleText.CharacterFormat.FontSize = 18
titleText.CharacterFormat.FontName = "Arial"
titleText.CharacterFormat.TextColor = Color.FromArgb(0xFF, 0x00, 0x71, 0xb6)
title.Format.HorizontalAlignment = HorizontalAlignment.Center
title.Format.AfterSpacing = 8

# 保存文档
document.SaveToFile("WithHeaderFooter.docx", FileFormat.Docx)
document.Close()

在这个示例中,我们定义了一个函数来处理页眉和页脚的创建。在页眉中,我们添加了图片和右对齐的斜体文本,并设置了底部边框。在页脚中,我们添加了图片以及动态页码字段。通过使用 AppendField() 方法并指定字段类型为 FieldPageFieldNumPages,我们可以自动显示当前页码和总页数。

添加书签

书签是 Word 文档中用于标记特定位置的有用功能,可以用于快速导航或作为超链接的目标。下面的示例展示了如何创建简单书签和嵌套书签。

python 复制代码
from spire.doc import *
from spire.doc.common import *

def CreateBookmark(section):
    """在文档中创建书签"""
    paragraph = section.AddParagraph()
    txtRange = paragraph.AppendText("以下示例演示如何在 Word 文档中创建书签。")
    txtRange.CharacterFormat.Italic = True

    section.AddParagraph()
    paragraph = section.AddParagraph()
    txtRange = paragraph.AppendText("创建简单书签")
    txtRange.CharacterFormat.TextColor = Color.get_CornflowerBlue()
    paragraph.ApplyStyle(BuiltinStyle.Heading2)

    # 创建简单书签
    section.AddParagraph()
    paragraph = section.AddParagraph()
    paragraph.AppendBookmarkStart("SimpleCreateBookmark")
    paragraph.AppendText("这是一个简单书签。")
    paragraph.AppendBookmarkEnd("SimpleCreateBookmark")

    section.AddParagraph()
    paragraph = section.AddParagraph()
    txtRange = paragraph.AppendText("创建嵌套书签")
    txtRange.CharacterFormat.TextColor = Color.get_CornflowerBlue()
    paragraph.ApplyStyle(BuiltinStyle.Heading2)

    # 创建嵌套书签
    section.AddParagraph()
    paragraph = section.AddParagraph()
    paragraph.AppendBookmarkStart("Root")
    txtRange = paragraph.AppendText(" 这是根级别数据 ")
    txtRange.CharacterFormat.Italic = True
    paragraph.AppendBookmarkStart("NestedLevel1")
    txtRange = paragraph.AppendText(" 这是嵌套级别1 ")
    txtRange.CharacterFormat.Italic = True
    txtRange.CharacterFormat.TextColor = Color.get_DarkSlateGray()
    paragraph.AppendBookmarkStart("NestedLevel2")
    txtRange = paragraph.AppendText(" 这是嵌套级别2 ")
    txtRange.CharacterFormat.Italic = True
    txtRange.CharacterFormat.TextColor = Color.get_DimGray()
    paragraph.AppendBookmarkEnd("NestedLevel2")
    paragraph.AppendBookmarkEnd("NestedLevel1")
    paragraph.AppendBookmarkEnd("Root")

# 创建文档
document = Document()
section = document.AddSection()

CreateBookmark(section)

# 保存文档
document.SaveToFile("CreateBookmark.docx", FileFormat.Docx)
document.Close()

在这个示例中,我们演示了两种书签的创建方式。简单书签通过 AppendBookmarkStart()AppendBookmarkEnd() 方法包裹一段文本。嵌套书签则展示了如何在已有的书签内部创建新的书签,形成层次结构。这种嵌套结构对于组织复杂文档非常有用。

综合应用:创建完整的表单文档

结合上述所有技术,我们可以创建一个完整的表单文档。这个综合示例展示了如何将页面设置、页眉页脚、标题、描述文本和表格组合在一起,形成一个专业的表单文档。

python 复制代码
from spire.doc import *
from spire.doc.common import *
import xml.etree.ElementTree as ET

def CreateCompleteForm():
    """创建完整的表单文档"""
    # 创建文档
    document = Document()
    section = document.AddSection()

    # 页面设置
    section.PageSetup.PageSize = PageSize.A4()
    section.PageSetup.Margins.Top = 72
    section.PageSetup.Margins.Bottom = 72
    section.PageSetup.Margins.Left = 89.85
    section.PageSetup.Margins.Right = 89.85

    # 添加标题
    title = section.AddParagraph()
    titleText = title.AppendText("用户注册表单")
    titleText.CharacterFormat.FontSize = 18
    titleText.CharacterFormat.FontName = "Arial"
    titleText.CharacterFormat.TextColor = Color.FromArgb(0xFF, 0x00, 0x71, 0xb6)
    title.Format.HorizontalAlignment = HorizontalAlignment.Center
    title.Format.AfterSpacing = 8

    # 添加说明文本
    descriptionStyle = ParagraphStyle(document)
    descriptionStyle.Name = "description"
    descriptionStyle.CharacterFormat.FontSize = 12
    descriptionStyle.CharacterFormat.FontName = "Arial"
    descriptionStyle.CharacterFormat.TextColor = Color.FromArgb(0xFF, 0x00, 0x45, 0x8e)
    document.Styles.Add(descriptionStyle)

    p1 = section.AddParagraph()
    text1 = "请填写以下信息以完成注册。所有信息都将保密处理。"
    p1.AppendText(text1)
    p1.ApplyStyle(descriptionStyle.Name)
    p1.Format.AfterSpacing = 8

    # 添加表格用于表单字段
    table = section.AddTable()
    table.DefaultColumnsNumber = 2
    table.DefaultRowHeight = 20

    # 添加表头行
    row = table.AddRow(False)
    row.Cells[0].CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(0xFF, 0x00, 0x71, 0xb6)
    row.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle

    cellParagraph = row.Cells[0].AddParagraph()
    cellParagraph.AppendText("基本信息")
    cellParagraph.CharacterFormat.FontSize = 12
    cellParagraph.CharacterFormat.FontName = "Arial"
    cellParagraph.CharacterFormat.TextColor = Color.get_White()
    cellParagraph.CharacterFormat.Bold = True

    # 合并单元格
    table.ApplyHorizontalMerge(row.GetRowIndex(), 0, 1)

    # 添加姓名字段
    fieldRow = table.AddRow(False)
    fieldRow.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle
    labelParagraph = fieldRow.Cells[0].AddParagraph()
    labelParagraph.AppendText("姓名:")
    labelParagraph.CharacterFormat.FontSize = 11
    labelParagraph.CharacterFormat.FontName = "Arial"
    labelParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right

    fieldRow.Cells[1].CellFormat.VerticalAlignment = VerticalAlignment.Middle
    fieldParagraph = fieldRow.Cells[1].AddParagraph()
    field = fieldParagraph.AppendField("name", FieldType.FieldFormTextInput)
    if isinstance(field, TextFormField):
        field.DefaultText = ""
        field.Text = ""

    # 添加邮箱字段
    emailRow = table.AddRow(False)
## emailRow.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle
    emailLabel = emailRow.Cells[0].AddParagraph()
    emailLabel.AppendText("邮箱:")
    emailLabel.CharacterFormat.FontSize = 11
    emailLabel.CharacterFormat.FontName = "Arial"
    emailLabel.Format.HorizontalAlignment = HorizontalAlignment.Right

    emailRow.Cells[1].CellFormat.VerticalAlignment = VerticalAlignment.Middle
    emailFieldPara = emailRow.Cells[1].AddParagraph()
    emailField = emailFieldPara.AppendField("email", FieldType.FieldFormTextInput)
    if isinstance(emailField, TextFormField):
        emailField.DefaultText = ""
        emailField.Text = ""

    # 将表格添加到节中
    section.Tables.Add(table)

    # 保存文档
    document.SaveToFile("CompleteForm.docx", FileFormat.Docx)
    document.Close()

# 执行创建表单
CreateCompleteForm()

这个综合示例展示了一个完整的用户注册表单的创建过程。我们首先设置页面布局,然后添加居中的标题和说明文本。接着创建一个表格来组织表单字段,包括带背景的表头行和包含文本输入字段的行。通过这种方式,我们可以创建出结构清晰、格式专业的表单文档。

小结

本文详细介绍了如何使用 Spire.Doc for Python 库从零开始创建 Word 文档。我们从最简单的 Hello World 示例开始,逐步学习了如何设置页面格式、添加格式化文本、创建表格、添加页眉页脚以及插入书签等核心功能。最后通过一个综合示例展示了如何将这些技术组合起来创建完整的表单文档。

通过这些示例,我们可以看到 Spire.Doc 提供了丰富而灵活的 API 来满足各种文档创建需求。无论是简单的文本记录还是复杂的结构化文档,都可以通过编程方式高效地生成。掌握这些技术后,您可以将其应用到报告生成、合同制作、表单设计等各种实际场景中,大幅提升文档处理的自动化水平。

相关推荐
Csvn6 小时前
Python 两大经典坑点 —— 可变默认参数 & 闭包延迟绑定
后端·python
曲幽7 小时前
别再用网页翻译看源码了!你的私人翻译神器LibreTranslate,部署避坑指南来了
python·docker·web·pot·translate·libretranslate·arogstranslate
用户556918817539 小时前
#从脚本到独立程序:Python + Playwright 批量抓取的完整踩坑记录
python·自动化运维
兵慌码乱1 天前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2
luckdewei1 天前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python
aqi001 天前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn1 天前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵2 天前
[Python] 从《千字文》中随机挑选汉字
后端·python