Python 自动化 Word 文本框处理:创建、定位、填充内容与管理

文本框是 Word 中一种可以自由浮动的容器,常用于制作侧边栏、强调说明、票据样式,或在固定位置放置图片和表格。相比普通段落,文本框能脱离正文流独立定位,排版上更灵活。手动插入并逐个调整样式很繁琐,尤其当文档需要大量样式统一的文本框时。

用 Python 可以批量插入、格式化文本框,还能在文本框内放置图片和表格、提取其中的文字、按需删除。本文以 Spire.Doc for Python 为例,介绍这些常见操作。

环境准备

安装 Spire.Doc 库:

bash 复制代码
pip install Spire.Doc

在脚本中引入模块:

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

插入文本框并设置基本样式

文本框通过段落的 AppendTextBox() 方法插入,参数是宽度和高度(单位磅)。插入后,通过 Format 属性设置边框颜色、线型、填充色等基本样式,通过 Body 向文本框内写入内容:

python 复制代码
document = Document()
section = document.AddSection()
paragraph = section.AddParagraph()

# 插入一个 240x35 磅的文本框
textBox = paragraph.AppendTextBox(240, 35)

# 设置边框与填充样式
textBox.Format.HorizontalAlignment = ShapeHorizontalAlignment.Left
textBox.Format.LineColor = Color.get_Gray()
textBox.Format.LineStyle = TextBoxLineStyle.Simple
textBox.Format.FillColor = Color.get_DarkSeaGreen()

# 在文本框内写入文字并设置格式
para = textBox.Body.AddParagraph()
textRange = para.AppendText("文档中的第一个文本框")
textRange.CharacterFormat.FontName = "Microsoft YaHei"
textRange.CharacterFormat.FontSize = 14
textRange.CharacterFormat.TextColor = Color.get_White()
para.Format.HorizontalAlignment = HorizontalAlignment.Center

document.SaveToFile("文本框.docx", FileFormat.Docx)
document.Close()

TextBoxLineStyle 提供多种线型(SimpleThinThickTriple 等),LineDashing 则控制虚实线(SolidDotDashDotDot 等),二者配合可以做出不同的边框效果。

精确控制位置和边框

默认情况下文本框按段落流排列。若要把它固定在页面的特定位置,需要指定定位基准和坐标:

python 复制代码
document = Document()
section = document.AddSection()
textBox = section.AddParagraph().AppendTextBox(310, 90)

# 在文本框内写入文字
para = textBox.Body.AddParagraph()
textRange = para.AppendText("Spire.Doc 提供了简单有效的方法......")
textRange.CharacterFormat.FontSize = 13

# 以页面为基准设置精确位置
textBox.Format.HorizontalOrigin = HorizontalOrigin.Page
textBox.Format.HorizontalPosition = 120
textBox.Format.VerticalOrigin = VerticalOrigin.Page
textBox.Format.VerticalPosition = 100

# 设置边框线型、颜色与粗细
textBox.Format.LineStyle = TextBoxLineStyle.Double
textBox.Format.LineColor = Color.get_CornflowerBlue()
textBox.Format.LineDashing = LineDashing.Solid
textBox.Format.LineWidth = 5

# 设置文本框内边距
textBox.Format.InternalMargin.Top = 15
textBox.Format.InternalMargin.Bottom = 10
textBox.Format.InternalMargin.Left = 12
textBox.Format.InternalMargin.Right = 10

document.SaveToFile("文本框格式.docx", FileFormat.Docx)
document.Close()

HorizontalOrigin / VerticalOrigin 决定坐标以页面还是其他对象为基准,HorizontalPosition / VerticalPosition 给出具体坐标。InternalMargin 控制文字与边框之间的内边距,四个方向可分别设置。

在文本框中插入图片

文本框不仅容纳文字,还能用图片填充整个背景:

python 复制代码
document = Document()
section = document.AddSection()
textBox = section.AddParagraph().AppendTextBox(220, 220)

# 设置文本框位置
textBox.Format.HorizontalOrigin = HorizontalOrigin.Page
textBox.Format.HorizontalPosition = 50
textBox.Format.VerticalOrigin = VerticalOrigin.Page
textBox.Format.VerticalPosition = 50

# 将文本框填充效果设为图片
textBox.Format.FillEfects.Type = BackgroundType.Picture
textBox.Format.FillEfects.SetPicture("logo.png")

document.SaveToFile("图片文本框.docx", FileFormat.Docx)
document.Close()

FillEfects.Type 设为 BackgroundType.Picture 后,FillEfects.SetPicture() 会把指定图片铺满文本框,相当于用图片作为文本框的底图。

在文本框中插入表格

文本框内部可以包含表格,适合制作票据、明细卡这类需要对齐的内容:

python 复制代码
document = Document()
section = document.AddSection()
textBox = section.AddParagraph().AppendTextBox(300, 100)

textBox.Format.HorizontalOrigin = HorizontalOrigin.Page
textBox.Format.HorizontalPosition = 140
textBox.Format.VerticalOrigin = VerticalOrigin.Page
textBox.Format.VerticalPosition = 50

# 在文本框内添加标题
title = textBox.Body.AddParagraph().AppendText("Table 1")

# 在文本框内插入表格并指定行列数
table = textBox.Body.AddTable(True)
table.ResetCells(4, 4)

data = [
    ["Name", "Age", "Gender", "ID"],
    ["John", "28", "Male", "0023"],
    ["Steve", "30", "Male", "0024"],
    ["Lucy", "26", "Female", "0025"],
]
for i in range(4):
    for j in range(4):
        table.Rows[i].Cells[j].AddParagraph().AppendText(data[i][j])

# 应用内置表格样式
table.ApplyStyle(DefaultTableStyle.TableColorful2)

document.SaveToFile("表格文本框.docx", FileFormat.Docx)
document.Close()

Body.AddTable(True) 在文本框内创建表格,ResetCells() 定义行数和列数,ApplyStyle() 套用预设样式。表格同样可以逐单元格写入数据。

提取文本框中的文字

反向操作也很常见:从已有文档中把文本框里的内容读出来。文本框分布在段落的子对象中,需要逐层遍历:

python 复制代码
document = Document()
document.LoadFromFile("含文本框的文档.docx")

if document.TextBoxes.Count > 0:
    with open("提取结果.txt", "w", encoding="utf-8") as f:
        for i in range(document.Sections.Count):
            section = document.Sections.get_Item(i)
            for j in range(section.Paragraphs.Count):
                paragraph = section.Paragraphs.get_Item(j)
                for k in range(paragraph.ChildObjects.Count):
                    obj = paragraph.ChildObjects.get_Item(k)
                    if obj.DocumentObjectType == DocumentObjectType.TextBox:
                        textbox = obj
                        for x in range(textbox.ChildObjects.Count):
                            child = textbox.ChildObjects.get_Item(x)
                            if child.DocumentObjectType == DocumentObjectType.Paragraph:
                                f.write(child.Text)
                            elif child.DocumentObjectType == DocumentObjectType.Table:
                                table = child
                                for r in range(table.Rows.Count):
                                    for c in range(table.Rows[r].Cells.Count):
                                        for p in range(table.Rows[r].Cells[c].Paragraphs.Count):
                                            f.write(table.Rows[r].Cells[c].Paragraphs.get_Item(p).Text)

document.Close()

判断对象类型靠 DocumentObjectType 枚举:文本框内的内容既可能是段落,也可能是表格,需分别处理。这段逻辑可以用于批量汇总散落在多个文本框里的信息。

删除文本框

不需要的文本框可以按索引删除,或一次性清空:

python 复制代码
document = Document()
document.LoadFromFile("模板.docx")

# 删除第一个文本框
document.TextBoxes.RemoveAt(0)

# 如需清空所有文本框,使用:
# document.TextBoxes.Clear()

document.SaveToFile("删除文本框.docx", FileFormat.Docx)
document.Close()

TextBoxes 集合保存了文档中的全部文本框,RemoveAt() 按索引删除,Clear() 清空所有。

实用提示

  • 文本框尺寸和坐标单位都是磅(point),1 英寸约等于 72 磅,需要换算时注意。
  • 固定定位时先设 HorizontalOrigin / VerticalOriginPage,再设 Position,否则坐标可能按其他基准计算。
  • 中文文档建议给文字显式指定中文字体(如 Microsoft YaHei),避免不同机器上字体回退导致排版变化。
  • 处理完及时调用 Close() 释放文件句柄。

总结

本文介绍了用 Python 在 Word 文档中操作文本框的完整流程:用 AppendTextBox() 插入,用 Format 属性控制边框、填充和精确定位,在文本框内插入图片和表格,通过遍历 DocumentObjectType 提取文本框内容,以及用 TextBoxes 集合删除文本框。掌握这些方法后,可以把繁琐的文本框排版交给脚本批量完成,让文档排版更统一高效。

相关推荐
用户8356290780517 小时前
使用 Python 在 Word 文档中创建自定义图表
后端·python
Profile排查笔记8 小时前
JavaScript 实现浏览器指纹生成:基础字段、Canvas 采样与 SHA-256 摘要
前端·人工智能·后端·自动化
GoGeekBaird8 小时前
我给 DeepSeek Harness 造了个铸造台
后端
YOU OU8 小时前
Spring Cloud概述
后端·spring·spring cloud
半个落月8 小时前
React JWT 登录鉴权实战:Mock、Zustand、Axios 与路由守卫全流程
后端·react.js
XingXingXxx8 小时前
Skill 能自己变强吗?从轨迹归纳到文本空间优化的进化之路
后端
jvmind_dev8 小时前
频繁 new JedisCluster 之后,对象池为什么回不去了?
java·后端
掘金者阿豪8 小时前
给你的AI龙虾打造一间像素办公室!Star Office UI部署+公网访问完整教程
后端
kyrie_sakura8 小时前
python学习笔记11 -- 进程和线程
笔记·python·学习