python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python JSON数据写入Word

使用Python实现写入JSON数据到Word文档

作者:大丸子

本文将介绍如何使用 Python 读取 JSON 数据,并将其以表格、段落等结构化形式自动写入 Word 文档,整个过程可以实现自动化,适用于 API 数据报告生成、配置文档输出、数据库导出数据格式化、业务数据定期汇总等多个场景,希望对大家有所帮助

在现代数据驱动的业务场景中,JSON 作为最通用的数据交换格式,广泛用于 API 响应、配置文件、数据库导出等场景。然而,当需要将这些结构化数据以专业、可读的形式呈现给非技术人员或用于正式报告时,直接展示 JSON 原文显然不够友好。许多用户尝试手动将 JSON 数据逐条复制到 Word 文档中,但当数据量大、结构复杂或需要定期更新时,手动操作不仅效率低下,还极易出现数据遗漏、格式混乱等问题。

本文将介绍如何使用 Python 读取 JSON 数据,并将其以表格、段落等结构化形式自动写入 Word 文档。整个过程可以实现自动化,适用于 API 数据报告生成、配置文档输出、数据库导出数据格式化、业务数据定期汇总等多个场景。

本文使用的方法需要用到 Free Spire.Doc for Python,可通过 pip 安装:

pip install spire.doc.free

1. 读取 JSON 数据并写入 Word 段落

当 JSON 数据为简单的键值对结构时,我们可以将每个字段以段落形式写入 Word 文档,适合生成配置说明、个人信息卡片等场景。

import json
from spire.doc import *
from spire.doc.common import *

# JSON 数据(实际场景中可从文件或 API 获取)
json_data = {
    "项目名称": "智慧城市数据平台",
    "版本": "v3.2.1",
    "负责人": "张伟",
    "状态": "进行中",
    "启动日期": "2024-01-15",
    "预计完成": "2024-12-31",
    "技术栈": "Python, Kafka, PostgreSQL, Docker",
    "描述": "基于物联网传感器数据构建城市级实时监控与分析平台,涵盖交通、环境、能源三大领域。"
}

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

# 添加标题
title = section.AddParagraph()
title_text = title.AppendText("项目信息概览")
title.Format.HorizontalAlignment = HorizontalAlignment.Center
title_text.CharacterFormat.FontName = "微软雅黑"
title_text.CharacterFormat.Bold = True
title_text.CharacterFormat.FontSize = 18
section.AddParagraph()

# 遍历 JSON 数据,逐条写入段落
for key, value in json_data.items():
    para = section.AddParagraph()
    text_range = para.AppendText(f"{key}:{value}")
    text_range.CharacterFormat.FontSize = 12
    text_range.CharacterFormat.FontName = "微软雅黑"

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

文档预览:

说明:

此方式适合数据量较少、结构扁平的 JSON 数据呈现。

2. 将 JSON 数组数据写入 Word 表格

在实际业务中,JSON 数据常以数组形式存在,例如员工列表、订单记录、产品目录等。此时,将数据写入 Word 表格是最直观、最专业的呈现方式。

2.1 基础表格:员工信息列表

import json
from spire.doc import *
from spire.doc.common import *

# JSON 数组数据
json_employees = [
    {"姓名": "张三", "部门": "技术部", "职位": "高级工程师", "入职日期": "2020-03-15", "薪资": "25000"},
    {"姓名": "李四", "部门": "市场部", "职位": "市场经理", "入职日期": "2019-06-20", "薪资": "22000"},
    {"姓名": "王五", "部门": "人力资源部", "职位": "HR专员", "入职日期": "2021-01-10", "薪资": "15000"},
    {"姓名": "赵六", "部门": "财务部", "职位": "财务主管", "入职日期": "2018-11-05", "薪资": "20000"},
    {"姓名": "钱七", "部门": "技术部", "职位": "产品经理", "入职日期": "2020-08-22", "薪资": "23000"},
]

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

# 添加标题
title = section.AddParagraph()
title_text = title.AppendText("员工信息表")
title.Format.HorizontalAlignment = HorizontalAlignment.Center
title_text.CharacterFormat.Bold = True
title_text.CharacterFormat.FontSize = 18
section.AddParagraph()

# 提取表头(JSON 对象的所有键)
headers = list(json_employees[0].keys())

# 创建表格
table = section.AddTable(True)
table.ResetCells(len(json_employees) + 1, len(headers))

# 设置表头行
header_row = table.Rows[0]
header_row.IsHeader = True
header_row.Height = 30
header_row.HeightType = TableRowHeightType.Exactly

for i, header in enumerate(headers):
    cell = header_row.Cells[i]
    cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
    cell.CellFormat.Shading.BackgroundPatternColor = Color.get_Gray()
    paragraph = cell.AddParagraph()
    paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
    text_range = paragraph.AppendText(header)
    text_range.CharacterFormat.Bold = True
    text_range.CharacterFormat.FontSize = 12

# 填充数据行
for row_idx, employee in enumerate(json_employees):
    data_row = table.Rows[row_idx + 1]
    data_row.Height = 25
    data_row.HeightType = TableRowHeightType.Exactly

    for col_idx, key in enumerate(headers):
        cell = data_row.Cells[col_idx]
        cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
        cell.CellFormat.Shading.BackgroundPatternColor = Color.Empty()
        paragraph = cell.AddParagraph()
        paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
        paragraph.AppendText(str(employee[key]))

# 设置隔行变色
for row_idx in range(1, table.Rows.Count):
    if row_idx % 2 == 0:
        row = table.Rows[row_idx]
        for i in range(row.Cells.Count):
            row.Cells[i].CellFormat.Shading.BackgroundPatternColor = Color.get_LightBlue()

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

文档预览:

Python写入JSON数组到Word表格

说明:

2.2 带样式的表格:季度销售数据

当 JSON 数据用于正式报告时,我们可以进一步应用预设样式和边框设置,使表格更具专业性:

import json
from spire.doc import *
from spire.doc.common import *

# JSON 销售数据
json_sales = [
    {"产品名称": "笔记本电脑", "第一季度": "120万", "第二季度": "135万", "第三季度": "150万", "第四季度": "168万"},
    {"产品名称": "平板电脑", "第一季度": "85万", "第二季度": "92万", "第三季度": "105万", "第四季度": "118万"},
    {"产品名称": "智能手机", "第一季度": "200万", "第二季度": "220万", "第三季度": "245万", "第四季度": "280万"},
    {"产品名称": "智能手表", "第一季度": "45万", "第二季度": "52万", "第三季度": "60万", "第四季度": "72万"},
]

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

# 添加标题
title = section.AddParagraph()
title_text = title.AppendText("2024年度季度销售报表")
title.Format.HorizontalAlignment = HorizontalAlignment.Center
title_text.CharacterFormat.Bold = True
title_text.CharacterFormat.FontSize = 18
section.AddParagraph()

# 提取表头
headers = list(json_sales[0].keys())

# 创建表格
table = section.AddTable(True)
table.ResetCells(len(json_sales) + 1, len(headers))

# 填充表头
for i, header in enumerate(headers):
    cell = table.Rows[0].Cells[i]
    cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
    cell.CellFormat.Shading.BackgroundPatternColor = Color.get_DarkSeaGreen()
    paragraph = cell.AddParagraph()
    paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
    text_range = paragraph.AppendText(header)
    text_range.CharacterFormat.Bold = True
    text_range.CharacterFormat.FontSize = 12
    text_range.CharacterFormat.TextColor = Color.get_White()

# 填充数据
for row_idx, item in enumerate(json_sales):
    for col_idx, key in enumerate(headers):
        cell = table.Rows[row_idx + 1].Cells[col_idx]
        cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
        paragraph = cell.AddParagraph()
        paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
        paragraph.AppendText(str(item[key]))

# 应用预设表格样式
table.ApplyStyle(DefaultTableStyle.ColorfulListAccent1)

# 设置边框
table.Format.Borders.BorderType = BorderStyle.Single
table.Format.Borders.LineWidth = 1.0
table.Format.Borders.Color = Color.get_Black()

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

文档预览:

Python写入JSON数据到Word带样式表格

说明:

3. 处理嵌套 JSON 数据:合并单元格表格

实际业务中的 JSON 数据往往具有嵌套结构,例如包含分类信息的产品目录。我们可以通过合并单元格来呈现层级关系:

import json
from spire.doc import *
from spire.doc.common import *

# 嵌套 JSON 数据
json_catalog = {
    "电子产品": [
        {"型号": "SP-2024", "名称": "智能手机", "价格": "3999元"},
        {"型号": "TB-2024", "名称": "平板电脑", "价格": "2999元"},
    ],
    "家居用品": [
        {"型号": "RC-2024", "名称": "电饭煲", "价格": "599元"},
        {"型号": "AP-2024", "名称": "空气净化器", "价格": "1299元"},
    ],
    "办公用品": [
        {"型号": "PR-2024", "名称": "打印机", "价格": "1599元"},
        {"型号": "SH-2024", "名称": "碎纸机", "价格": "399元"},
    ],
}

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

# 添加标题
title = section.AddParagraph()
title_text = title.AppendText("产品目录")
title.Format.HorizontalAlignment = HorizontalAlignment.Center
title_text.CharacterFormat.Bold = True
title_text.CharacterFormat.FontSize = 18
section.AddParagraph()

# 计算总行数(表头1行 + 每个分类的产品行数)
total_rows = 1 + sum(len(items) for items in json_catalog.values())
col_count = 4  # 分类 + 型号 + 名称 + 价格

# 创建表格
table = section.AddTable(True)
table.ResetCells(total_rows, col_count)

# 填充表头
headers = ["分类", "型号", "名称", "价格"]
for i, header in enumerate(headers):
    cell = table.Rows[0].Cells[i]
    cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
    cell.CellFormat.Shading.BackgroundPatternColor = Color.get_Gray()
    paragraph = cell.AddParagraph()
    paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
    text_range = paragraph.AppendText(header)
    text_range.CharacterFormat.Bold = True

# 填充分类数据并合并分类列单元格
current_row = 1
for category, items in json_catalog.items():
    start_row = current_row
    for item in items:
        row = table.Rows[current_row]
        row.Cells[1].AddParagraph().AppendText(item["型号"])
        row.Cells[2].AddParagraph().AppendText(item["名称"])
        row.Cells[3].AddParagraph().AppendText(item["价格"])
        current_row += 1

    # 在分类列写入类别名称
    table.Rows[start_row].Cells[0].AddParagraph().AppendText(category)

    # 如果该分类有多行,合并分类列的单元格
    if len(items) > 1:
        table.ApplyVerticalMerge(0, start_row, start_row + len(items) - 1)

    # 设置分类列单元格居中
    table.Rows[start_row].Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle
    table.Rows[start_row].Cells[0].Paragraphs[0].Format.HorizontalAlignment = HorizontalAlignment.Center

# 应用表格样式
table.ApplyStyle(DefaultTableStyle.ColorfulGridAccent3)

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

文档预览:

Python写入嵌套JSON数据到Word合并单元格表格

说明:

4. 从 JSON 文件批量写入多个表格

在实际应用中,JSON 数据可能来自文件或 API,且包含多个数据集。以下示例展示如何从 JSON 文件读取数据并批量写入多个表格到同一 Word 文档:

import json
from spire.doc import *
from spire.doc.common import *

# 模拟从 JSON 文件读取的数据(实际场景使用 json.load())
json_file_data = {
    "员工信息": [
        {"姓名": "张三", "部门": "技术部", "职位": "工程师"},
        {"姓名": "李四", "部门": "市场部", "职位": "经理"},
        {"姓名": "王五", "部门": "财务部", "职位": "会计"},
    ],
    "项目列表": [
        {"项目": "数据平台", "状态": "进行中", "进度": "75%"},
        {"项目": "移动应用", "状态": "已完成", "进度": "100%"},
        {"项目": "AI模型", "状态": "规划中", "进度": "10%"},
    ],
    "设备清单": [
        {"设备": "服务器A", "IP": "192.168.1.10", "状态": "运行中"},
        {"设备": "服务器B", "IP": "192.168.1.11", "状态": "维护中"},
        {"设备": "交换机", "IP": "192.168.1.1", "状态": "运行中"},
    ],
}

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

# 添加文档标题
doc_title = section.AddParagraph()
doc_title_text = doc_title.AppendText("数据汇总报告")
doc_title.Format.HorizontalAlignment = HorizontalAlignment.Center
doc_title_text.CharacterFormat.Bold = True
doc_title_text.CharacterFormat.FontSize = 22
section.AddParagraph()

# 遍历每个数据集,创建对应的表格
for table_name, records in json_file_data.items():
    # 添加表格标题
    table_title = section.AddParagraph()
    table_title_text = table_title.AppendText(table_name)
    table_title_text.CharacterFormat.Bold = True
    table_title_text.CharacterFormat.FontSize = 14
    section.AddParagraph()

    # 提取表头
    headers = list(records[0].keys())

    # 创建表格
    table = section.AddTable(True)
    table.ResetCells(len(records) + 1, len(headers))

    # 填充表头
    for i, header in enumerate(headers):
        cell = table.Rows[0].Cells[i]
        cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
        cell.CellFormat.Shading.BackgroundPatternColor = Color.get_Gray()
        paragraph = cell.AddParagraph()
        paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
        text_range = paragraph.AppendText(header)
        text_range.CharacterFormat.Bold = True

    # 填充数据
    for row_idx, record in enumerate(records):
        for col_idx, key in enumerate(headers):
            cell = table.Rows[row_idx + 1].Cells[col_idx]
            cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
            paragraph = cell.AddParagraph()
            paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
            paragraph.AppendText(str(record[key]))

    # 应用表格样式
    table.ApplyStyle(DefaultTableStyle.ColorfulListAccent1)
    table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)

    # 添加空行分隔
    section.AddParagraph()

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

文档预览:

Python从JSON文件批量写入多个Word表格

说明:

关键类与方法解析

类 / 方法 / 属性说明
DocumentWord 文档对象,支持创建、加载和保存文档
Document.AddSection()添加文档节,作为表格和段落的容器
Document.SaveToFile()将文档保存到指定文件路径
Section.AddTable()在节中创建新表格
Section.AddParagraph()在节中添加段落
Table.ResetCells(rows, cols)根据行列数初始化表格结构
Table.ApplyStyle()应用预设的表格样式
Table.ApplyHorizontalMerge()水平合并单元格
Table.ApplyVerticalMerge()垂直合并单元格
Table.AutoFit()自动调整表格宽度
Table.Rows获取表格行集合
TableRow.Cells获取行中的单元格集合
TableRow.IsHeader标记行为表头行
Cell.AddParagraph()在单元格中添加段落
Cell.CellFormat获取单元格格式对象
CellFormat.Shading.BackgroundPatternColor设置单元格背景颜色
CellFormat.VerticalAlignment设置单元格垂直对齐方式
Paragraph.AppendText()向段落追加文本
Paragraph.Format.HorizontalAlignment设置段落水平对齐方式
TextRange.CharacterFormat获取文本格式对象
CharacterFormat.Bold设置文本是否加粗
CharacterFormat.FontSize设置字体大小
CharacterFormat.FontName设置字体名称
DefaultTableStyle预设表格样式枚举
AutoFitBehaviorType表格自动调整行为枚举
FileFormat文件格式枚举

总结

通过本文示例,你已经了解如何使用 Python 将 JSON 数据以多种形式写入 Word 文档。从简单的键值对段落呈现,到结构化的表格生成,再到嵌套数据的合并单元格处理和批量数据集写入,整个过程高度自动化,特别适用于 API 数据报告、配置文档输出、业务数据定期汇总等场景。

相比手动复制粘贴或使用在线转换工具,代码方式具有批量处理、格式统一、可重复执行等优势。你可以在此基础上扩展更多能力,例如从 REST API 实时获取 JSON 数据并生成报告、结合定时任务实现自动化文档更新、添加图表可视化等。

如果你正在处理大量结构化数据的文档生成需求,这种基于 Python 的方案将为你的工作带来显著提升。

到此这篇关于使用Python实现写入JSON数据到Word文档的文章就介绍到这了,更多相关Python JSON数据写入Word内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文