Word 文档面向人类阅读,JSON 面向程序消费。把 Word 转成 JSON,本质上是一次结构映射:段落、表格、标题等文档组件要翻译成键值对与数组。下面按三种粒度给出实现:只取段落文本、只取表格对象数组、保留文档顺序与内容类型的层级 JSON。三种方式共用加载文档、按节遍历、读取内容、序列化输出这套基础 API,差异在遍历粒度与字段组织。
环境准备
安装文档处理库:该库支持 .doc 与 .docx 读写,运行时不要求本机安装 Office。示例路径可按实际文件调整。结构遍历和类型判断还需导入 spire.doc.common,否则 Paragraph、Table 等类型不可用,isinstance 判断会失败。
方法一:提取段落文本为 JSON 数组
适合全文索引、文本向量化等下游只消费纯文本的场景。思路是遍历文档的节与段落,过滤空白段落,再序列化。Word 文档层级为文档包含若干节,每节包含若干段落,逐层遍历可以控制提取范围。- import json
- from spire.doc import Document
- from spire.doc.common import *
- input_file = '项目报告.docx'
- output_file = 'paragraphs.json'
- document = Document()
- document.LoadFromFile(input_file)
- paragraphs = []
- 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)
- text = paragraph.Text
- if text.strip():
- paragraphs.append(text)
- document.Close()
- result = {
- 'source': input_file,
- 'paragraph_count': len(paragraphs),
- 'paragraphs': paragraphs
- }
- with open(output_file, 'w', encoding='utf-8') as f:
- json.dump(result, f, indent=2, ensure_ascii=False)
复制代码 输出包含 source、paragraph_count 和 paragraphs 三个字段。局限是标题、正文、列表项没有区分,文档层级信息丢失;若后续需要识别内容类型,应选择更细粒度方案。
方法二:将 Word 表格转为 JSON 对象数组
报表、发票、产品清单等文档中,表格常承载主要结构化数据。Word 表格有行列结构,首行通常为列标题,后续行为数据记录,适合映射为 JSON 对象数组。以下代码遍历所有表格,以首行为字段名,将每一数据行转为对象。对列数与表头长度不一致的情况做兜底,超出表头范围的列以 Column_{c} 命名,避免索引越界。- import json
- from spire.doc import Document
- from spire.doc.common import *
- input_file = '销售数据.docx'
- output_file = 'tables.json'
- document = Document()
- document.LoadFromFile(input_file)
- all_tables = []
- for i in range(document.Sections.Count):
- section = document.Sections.get_Item(i)
- for t in range(section.Tables.Count):
- table = section.Tables.get_Item(t)
- rows_data = []
- if table.Rows.Count < 2:
- continue
- header_row = table.Rows[0]
- headers = []
- for c in range(header_row.Cells.Count):
- cell_text = header_row.Cells[c].Paragraphs[0].Text.strip()
- headers.append(cell_text)
- for r in range(1, table.Rows.Count):
- row = table.Rows[r]
- row_dict = {}
- for c in range(row.Cells.Count):
- cell_text = row.Cells[c].Paragraphs[0].Text.strip()
- row_dict[headers[c] if c < len(headers) else f'Column_{c}'] = cell_text
- rows_data.append(row_dict)
- all_tables.append({
- 'table_index': t,
- 'headers': headers,
- 'row_count': len(rows_data),
- 'rows': rows_data
- })
- document.Close()
- result = {
- 'source': input_file,
- 'table_count': len(all_tables),
- 'tables': all_tables
- }
- with open(output_file, 'w', encoding='utf-8') as f:
- json.dump(result, f, indent=2, ensure_ascii=False)
复制代码 输出包含 table_count 与 tables;每张表记录 table_index、headers、row_count、rows。row_count 便于判断空表。表格为主时,这种 JSON 可直接导入数据库或数据分析工具,省去手动解析文本。
方法三:保留文档结构的层级化 JSON
前两种方法一个只拿文本,一个只拿表格。若目标是为 RAG 管道或知识库准备数据,更合理的是保留文档原始顺序与内容类型,让标题、段落、表格在 JSON 中各得其所。section.Body.ChildObjects 可按文档顺序返回所有元素,而非分别遍历段落集合或表格集合,因此标题与其下方正文的关联关系可以保留。实现时用段落的 StyleName 判断标题并映射级别;Word 标题样式名可能因模板或语言设置不同,如 Heading1、Heading 1 或中文的标题 1,实际项目查找前应先规范化样式名。- import json
- from spire.doc import *
- from spire.doc.common import *
- input_file = '项目报告.docx'
- output_file = 'structured_output.json'
- HEADING_STYLES = {
- 'Heading1': 1,
- 'Heading2': 2,
- 'Heading3': 3,
- 'Heading4': 4,
- }
- def get_heading_level(style_name):
- return HEADING_STYLES.get(style_name, None)
- def extract_table_data(table):
- rows_data = []
- if table.Rows.Count < 1:
- return {'headers': [], 'rows': []}
- header_row = table.Rows[0]
- headers = []
- for c in range(header_row.Cells.Count):
- headers.append(header_row.Cells[c].Paragraphs[0].Text.strip())
- for r in range(1, table.Rows.Count):
- row = table.Rows[r]
- row_dict = {}
- for c in range(row.Cells.Count):
- cell_text = row.Cells[c].Paragraphs[0].Text.strip()
- row_dict[headers[c] if c < len(headers) else f'Column_{c}'] = cell_text
- rows_data.append(row_dict)
- return {'headers': headers, 'rows': rows_data}
- document = Document()
- document.LoadFromFile(input_file)
- sections_data = []
- for i in range(document.Sections.Count):
- section = document.Sections.get_Item(i)
- content_items = []
- for j in range(section.Body.ChildObjects.Count):
- obj = section.Body.ChildObjects.get_Item(j)
- if isinstance(obj, Paragraph):
- text = obj.Text.strip()
- if not text:
- continue
- heading_level = get_heading_level(obj.StyleName)
- if heading_level:
- content_items.append({
- 'type': 'heading',
- 'level': heading_level,
- 'text': text
- })
- else:
- content_items.append({
- 'type': 'paragraph',
- 'text': text
- })
- elif isinstance(obj, Table):
- table_data = extract_table_data(obj)
- content_items.append({
- 'type': 'table',
- 'row_count': len(table_data['rows']),
- 'data': table_data
- })
- sections_data.append({
- 'section_index': i,
- 'content': content_items
- })
- document.Close()
- result = {
- 'source': input_file,
- 'section_count': len(sections_data),
- 'sections': sections_data
- }
- with open(output_file, 'w', encoding='utf-8') as f:
- json.dump(result, f, indent=2, ensure_ascii=False)
复制代码 输出中每个内容项都带 type 字段:heading 带 level 与 text,paragraph 带 text,table 带 row_count 与 data。下游可据此决定处理方式:标题用于分段,段落用于嵌入,表格用于结构化抽取。按标题切分文档通常比按固定长度切分更利于检索。
如何选择
三种方法不是替代关系。只需纯文本做搜索索引,方法一足够;文档核心是表格数据,方法二直接产出可入库结构;要保留语义结构供下游智能处理,方法三的额外代码量值得。实际项目也可组合:先用方法三获取整体结构,再按 type 字段分别处理各类元素。
几点注意事项
标题样式名差异:不同模板或语言环境下可能为 Heading1、Heading 1、标题 1,来源不固定时可在 get_heading_level 中先小写化、去空格再查表。合并单元格:合并单元格会影响行列索引与 Cells.Count,上述代码按原始行列读取,复杂合并表需额外处理。空段落与页眉页脚:section.Paragraphs 默认不包含页眉页脚,若要提取应单独访问 section.HeadersFooters。大文档内存占用:一次性加载整份文档再序列化会给超大文件带来内存压力,必要时可按节分批读取并分段写入 JSON。
无论哪种方式,json.dump 的 ensure_ascii=False 都建议保留,否则中文会被转义为 Unicode 编码,虽不影响程序解析,但人工查看不便。若在分支中使用 isinstance(obj, Paragraph) 与 isinstance(obj, Table),务必导入 spire.doc.common。
总结
把 Word 转 JSON 没有唯一写法,先明确下游消费的是文本还是结构。全文检索或文本嵌入用段落数组;表格数据为主用表头映射对象数组;知识库或 RAG 管道用带 type 字段的层级结构。三种方式共享加载文档、按节遍历、读取段落与表格、序列化输出这套脉络,再针对合并单元格、标题样式、页眉页脚等细节处理,就能得到匹配业务需求的 JSON 输出。 |