
一份 Word 产品报告可能同时包含文字说明、参数表和产品照片。如果要把这些资料导入其他系统,参数表需要保留行列关系,照片需要保存成独立文件,作者和标题则可以直接从文档属性读取。
本文使用 Spire.Doc for Python 加载 Word 文档,演示如何读取指定段落和全文、将表格导出为 CSV、提取嵌入图片,以及获取文档元数据。五个示例共用同一段加载代码。
在终端执行以下命令安装 Spire.Doc for Python。
python -m pip install Spire.Doc准备一份包含普通段落、表格和嵌入图片的 input.docx,放在脚本的当前工作目录中。先写入下面的加载代码,再接上需要运行的示例。所有读取操作完成后,在脚本末尾调用 document.Close()。
from pathlib import Path
from spire.doc import Document
input_path = Path("input.docx")
output_dir = Path("output")
document = Document()
document.LoadFromFile(str(input_path))如果一批文档使用同一个模板,且摘要始终放在固定位置,就可以按节和段落的索引读取。下面的代码获取第一个节中的第四个段落。索引从 0 开始,因此对应的段落索引是 3。
section_index = 0
paragraph_index = 3
if section_index < document.Sections.Count:
section = document.Sections.get_Item(section_index)
if paragraph_index < section.Paragraphs.Count:
paragraph = section.Paragraphs.get_Item(paragraph_index)
print(paragraph.Text)
else:
print("指定的节中没有第 4 个段落。")
else:
print("文档中没有指定的节。")段落索引按 Word 的段落对象计数。一个段落在页面上自动换成三行,仍然只占一个索引。表格单元格里的段落可以通过该单元格的 Paragraphs 集合读取。
如果目的是全文检索、关键词统计或归档纯文本,可以直接调用 GetText(),再将结果写入 UTF-8 编码的 TXT 文件。
output_dir.mkdir(parents=True, exist_ok=True)
text_path = output_dir / "document.txt"
text_path.write_text(document.GetText(), encoding="utf-8")运行后会生成 output/document.txt。如果后续需要按表格的行和列处理数据,可以直接遍历 Word 表格对象。
通过 Section.Tables 可以取得对应节的表格,再逐行读取单元格。一个单元格可能包含多个段落,示例用换行符把这些段落拼接到同一个 CSV 字段中。原文用空格分隔并导出为 TXT,这里改用 Python 的 csv 模块,让包含逗号、引号或换行的字段也能正确写入。
import csv
table_dir = output_dir / "tables"
table_dir.mkdir(parents=True, exist_ok=True)
for section_index in range(document.Sections.Count):
section = document.Sections.get_Item(section_index)
for table_index in range(section.Tables.Count):
table = section.Tables.get_Item(table_index)
csv_path = table_dir / f"table_{section_index + 1}_{table_index + 1}.csv"
with csv_path.open("w", encoding="utf-8-sig", newline="") as file:
writer = csv.writer(file)
for row_index in range(table.Rows.Count):
row = table.Rows.get_Item(row_index)
values = []
for cell_index in range(row.Cells.Count):
cell = row.Cells.get_Item(cell_index)
paragraphs = [
cell.Paragraphs.get_Item(i).Text
for i in range(cell.Paragraphs.Count)
]
values.append("\n".join(paragraphs))
writer.writerow(values)例如,第一节的第二张表会保存为 output/tables/table_1_2.csv。CSV 保存的是逐行读取的单元格文本。如果原表有合并单元格,导出的各行可能有不同数量的字段。
图片可能出现在普通段落里,也可能藏在表格单元格中。可以从文档对象开始遍历,遇到可继续展开的对象就加入队列,遇到 DocPicture 就读取它的 ImageBytes。下面的示例直接写出库返回的字节,并根据常见文件签名确定扩展名。
from collections import deque
from spire.doc import DocPicture
from spire.doc.common import ICompositeObject
image_dir = output_dir / "images"
image_dir.mkdir(parents=True, exist_ok=True)
image_signatures = {
b"\x89PNG\r\n\x1a\n": ".png",
b"\xff\xd8\xff": ".jpg",
b"GIF87a": ".gif",
b"GIF89a": ".gif",
b"BM": ".bmp",
b"II*\x00": ".tif",
b"MM\x00*": ".tif",
}
pending = deque([document])
image_number = 0
while pending:
children = pending.popleft().ChildObjects
for index in range(children.Count):
child = children.get_Item(index)
if isinstance(child, DocPicture):
data = bytes(child.ImageBytes)
if not data:
continue
extension = next(
(ext for signature, ext in image_signatures.items()
if data.startswith(signature)),
".bin",
)
image_number += 1
(image_dir / f"image_{image_number:03d}{extension}").write_bytes(data)
elif isinstance(child, ICompositeObject):
pending.append(child)图片会保存到 output/images。例如,JPEG 数据会保存为 image_001.jpg。签名表中未列出的格式会以 .bin 保存,便于保留字节后再识别格式。
如果要给一批 Word 文件建立索引,可以通过 BuiltinDocumentProperties 读取作者、标题、主题等内置属性。下面选取六个常用字段并将结果输出到终端。
properties = document.BuiltinDocumentProperties
metadata = {
"标题": properties.Title,
"主题": properties.Subject,
"作者": properties.Author,
"公司": properties.Company,
"类别": properties.Category,
"关键词": properties.Keywords,
}
for name, value in metadata.items():
print(f"{name}:{value or '未填写'}")这里的标题取自 Word 的文档属性。即使正文第一行有醒目的标题,只要文档属性中的“标题”字段为空,示例仍会输出“未填写”。
固定模板中的字段可以按节和段落定位,全文检索可以直接使用 GetText()。当资料需要进入其他系统时,可以把表格导出为 CSV、把图片保存为独立文件,再用文档属性生成索引。处理一批 Word 文件时,可以复用同一套读取逻辑,并按源文件分别组织输出。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。