查看: 110|回复: 1

Python 自动化:将 JSON 数据写入 Word 表格与段落(附代码)

[复制链接]
发表于 2 小时前 | 显示全部楼层 |阅读模式
在现代业务场景中,JSON 是 API 响应、配置文件、数据库导出中最常用的数据格式。但将结构化数据呈现给非技术人员或用于正式报告时,直接展示 JSON 原文并不友好。手动复制粘贴效率低、易出错。本文介绍如何使用 Python 和 Free Spire.Doc for Python 库,自动将 JSON 数据写入 Word 文档,支持段落、表格、嵌套数据合并单元格,以及从文件批量生成多表格。

首先安装依赖库:
  1. pip install spire.doc.free
复制代码

一、读取 JSON 数据并写入 Word 段落
当 JSON 为简单键值对结构时,可以用段落形式输出每个字段,适合生成配置说明、信息卡片等。
  1. import json
  2. from spire.doc import *
  3. from spire.doc.common import *
  4. json_data = {
  5.     "项目名称": "智慧城市数据平台",
  6.     "版本": "v3.2.1",
  7.     "负责人": "张伟",
  8.     "状态": "进行中",
  9.     "启动日期": "2024-01-15",
  10.     "预计完成": "2024-12-31",
  11.     "技术栈": "Python, Kafka, PostgreSQL, Docker",
  12.     "描述": "基于物联网传感器数据构建城市级实时监控与分析平台"
  13. }
  14. document = Document()
  15. section = document.AddSection()
  16. # 添加标题
  17. title = section.AddParagraph()
  18. title_text = title.AppendText("项目信息概览")
  19. title.Format.HorizontalAlignment = HorizontalAlignment.Center
  20. title_text.CharacterFormat.FontName = "微软雅黑"
  21. title_text.CharacterFormat.Bold = True
  22. title_text.CharacterFormat.FontSize = 18
  23. section.AddParagraph()
  24. # 遍历键值对写入段落
  25. for key, value in json_data.items():
  26.     para = section.AddParagraph()
  27.     text_range = para.AppendText(f"{key}:{value}")
  28.     text_range.CharacterFormat.FontSize = 12
  29.     text_range.CharacterFormat.FontName = "微软雅黑"
  30. document.SaveToFile("ProjectInfo.docx", FileFormat.Docx)
  31. document.Close()
复制代码
说明:Document() 创建文档,AddSection() 添加节,AppendText() 写入内容,通过 CharacterFormat 设置字体字号。适合数据量少、扁平的 JSON。

二、将 JSON 数组数据写入 Word 表格
2.1 基础员工信息表
  1. import json
  2. from spire.doc import *
  3. from spire.doc.common import *
  4. json_employees = [
  5.     {"姓名": "张三", "部门": "技术部", "职位": "高级工程师", "入职日期": "2020-03-15", "薪资": "25000"},
  6.     {"姓名": "李四", "部门": "市场部", "职位": "市场经理", "入职日期": "2019-06-20", "薪资": "22000"},
  7.     {"姓名": "王五", "部门": "人力资源部", "职位": "HR专员", "入职日期": "2021-01-10", "薪资": "15000"},
  8.     {"姓名": "赵六", "部门": "财务部", "职位": "财务主管", "入职日期": "2018-11-05", "薪资": "20000"},
  9.     {"姓名": "钱七", "部门": "技术部", "职位": "产品经理", "入职日期": "2020-08-22", "薪资": "23000"}
  10. ]
  11. document = Document()
  12. section = document.AddSection()
  13. title = section.AddParagraph()
  14. title_text = title.AppendText("员工信息表")
  15. title.Format.HorizontalAlignment = HorizontalAlignment.Center
  16. title_text.CharacterFormat.Bold = True
  17. title_text.CharacterFormat.FontSize = 18
  18. section.AddParagraph()
  19. headers = list(json_employees[0].keys())
  20. table = section.AddTable(True)
  21. table.ResetCells(len(json_employees) + 1, len(headers))
  22. # 表头行
  23. header_row = table.Rows[0]
  24. header_row.IsHeader = True
  25. header_row.Height = 30
  26. header_row.HeightType = TableRowHeightType.Exactly
  27. for i, header in enumerate(headers):
  28.     cell = header_row.Cells[i]
  29.     cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
  30.     cell.CellFormat.Shading.BackgroundPatternColor = Color.get_Gray()
  31.     paragraph = cell.AddParagraph()
  32.     paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
  33.     text_range = paragraph.AppendText(header)
  34.     text_range.CharacterFormat.Bold = True
  35.     text_range.CharacterFormat.FontSize = 12
  36. # 数据行
  37. for row_idx, employee in enumerate(json_employees):
  38.     data_row = table.Rows[row_idx + 1]
  39.     data_row.Height = 25
  40.     data_row.HeightType = TableRowHeightType.Exactly
  41.     for col_idx, key in enumerate(headers):
  42.         cell = data_row.Cells[col_idx]
  43.         cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
  44.         paragraph = cell.AddParagraph()
  45.         paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
  46.         paragraph.AppendText(str(employee[key]))
  47. # 隔行变色
  48. for row_idx in range(1, table.Rows.Count):
  49.     if row_idx % 2 == 0:
  50.         row = table.Rows[row_idx]
  51.         for i in range(row.Cells.Count):
  52.             row.Cells[i].CellFormat.Shading.BackgroundPatternColor = Color.get_LightBlue()
  53. document.SaveToFile("EmployeeJsonTable.docx", FileFormat.Docx)
  54. document.Close()
复制代码
关键点:list(json_employees[0].keys()) 动态提取表头,ResetCells() 初始化表格,表头灰色背景粗体,数据居中并隔行变色。

2.2 带样式的季度销售表格
  1. import json
  2. from spire.doc import *
  3. from spire.doc.common import *
  4. json_sales = [
  5.     {"产品名称": "笔记本电脑", "第一季度": "120万", "第二季度": "135万", "第三季度": "150万", "第四季度": "168万"},
  6.     {"产品名称": "平板电脑", "第一季度": "85万", "第二季度": "92万", "第三季度": "105万", "第四季度": "118万"},
  7.     {"产品名称": "智能手机", "第一季度": "200万", "第二季度": "220万", "第三季度": "245万", "第四季度": "280万"},
  8.     {"产品名称": "智能手表", "第一季度": "45万", "第二季度": "52万", "第三季度": "60万", "第四季度": "72万"}
  9. ]
  10. document = Document()
  11. section = document.AddSection()
  12. title = section.AddParagraph()
  13. title_text = title.AppendText("2024年度季度销售报表")
  14. title.Format.HorizontalAlignment = HorizontalAlignment.Center
  15. title_text.CharacterFormat.Bold = True
  16. title_text.CharacterFormat.FontSize = 18
  17. section.AddParagraph()
  18. headers = list(json_sales[0].keys())
  19. table = section.AddTable(True)
  20. table.ResetCells(len(json_sales) + 1, len(headers))
  21. for i, header in enumerate(headers):
  22.     cell = table.Rows[0].Cells[i]
  23.     cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
  24.     cell.CellFormat.Shading.BackgroundPatternColor = Color.get_DarkSeaGreen()
  25.     paragraph = cell.AddParagraph()
  26.     paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
  27.     text_range = paragraph.AppendText(header)
  28.     text_range.CharacterFormat.Bold = True
  29.     text_range.CharacterFormat.FontSize = 12
  30.     text_range.CharacterFormat.TextColor = Color.get_White()
  31. for row_idx, item in enumerate(json_sales):
  32.     for col_idx, key in enumerate(headers):
  33.         cell = table.Rows[row_idx + 1].Cells[col_idx]
  34.         cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
  35.         paragraph = cell.AddParagraph()
  36.         paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
  37.         paragraph.AppendText(str(item[key]))
  38. table.ApplyStyle(DefaultTableStyle.ColorfulListAccent1)
  39. table.Format.Borders.BorderType = BorderStyle.Single
  40. table.Format.Borders.LineWidth = 1.0
  41. table.Format.Borders.Color = Color.get_Black()
  42. document.SaveToFile("SalesJsonReport.docx", FileFormat.Docx)
  43. document.Close()
复制代码
ApplyStyle() 快速应用预设样式,Format.Borders 自定义边框。深绿色表头配白色字增强层次。

三、处理嵌套 JSON 数据:合并单元格表格
实际数据常含嵌套结构,如产品分类。通过 ApplyVerticalMerge 合并分类列单元格实现层级关系。
  1. import json
  2. from spire.doc import *
  3. from spire.doc.common import *
  4. json_catalog = {
  5.     "电子产品": [
  6.         {"型号": "SP-2024", "名称": "智能手机", "价格": "3999元"},
  7.         {"型号": "TB-2024", "名称": "平板电脑", "价格": "2999元"}
  8.     ],
  9.     "家居用品": [
  10.         {"型号": "RC-2024", "名称": "电饭煲", "价格": "599元"},
  11.         {"型号": "AP-2024", "名称": "空气净化器", "价格": "1299元"}
  12.     ],
  13.     "办公用品": [
  14.         {"型号": "PR-2024", "名称": "打印机", "价格": "1599元"},
  15.         {"型号": "SH-2024", "名称": "碎纸机", "价格": "399元"}
  16.     ]
  17. }
  18. document = Document()
  19. section = document.AddSection()
  20. title = section.AddParagraph()
  21. title_text = title.AppendText("产品目录")
  22. title.Format.HorizontalAlignment = HorizontalAlignment.Center
  23. title_text.CharacterFormat.Bold = True
  24. title_text.CharacterFormat.FontSize = 18
  25. section.AddParagraph()
  26. total_rows = 1 + sum(len(items) for items in json_catalog.values())
  27. col_count = 4  # 分类、型号、名称、价格
  28. table = section.AddTable(True)
  29. table.ResetCells(total_rows, col_count)
  30. headers = ["分类", "型号", "名称", "价格"]
  31. for i, header in enumerate(headers):
  32.     cell = table.Rows[0].Cells[i]
  33.     cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
  34.     cell.CellFormat.Shading.BackgroundPatternColor = Color.get_Gray()
  35.     paragraph = cell.AddParagraph()
  36.     paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
  37.     text_range = paragraph.AppendText(header)
  38.     text_range.CharacterFormat.Bold = True
  39. current_row = 1
  40. for category, items in json_catalog.items():
  41.     start_row = current_row
  42.     for item in items:
  43.         row = table.Rows[current_row]
  44.         row.Cells[1].AddParagraph().AppendText(item["型号"])
  45.         row.Cells[2].AddParagraph().AppendText(item["名称"])
  46.         row.Cells[3].AddParagraph().AppendText(item["价格"])
  47.         current_row += 1
  48.     # 写入分类名并合并单元格
  49.     table.Rows[start_row].Cells[0].AddParagraph().AppendText(category)
  50.     if len(items) > 1:
  51.         table.ApplyVerticalMerge(0, start_row, start_row + len(items) - 1)
  52.     table.Rows[start_row].Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle
  53. table.ApplyStyle(DefaultTableStyle.ColorfulGridAccent3)
  54. document.SaveToFile("CatalogJsonTable.docx", FileFormat.Docx)
  55. document.Close()
复制代码
ApplyVerticalMerge(列索引, 起始行, 结束行) 垂直合并同一分类的单元格,更直观展示层级。

四、从 JSON 文件批量写入多个表格
同一 JSON 可包含多组数据集,循环创建各自独立的表格,适合生成汇总报告。
  1. import json
  2. from spire.doc import *
  3. from spire.doc.common import *
  4. json_file_data = {
  5.     "员工信息": [
  6.         {"姓名": "张三", "部门": "技术部", "职位": "工程师"},
  7.         {"姓名": "李四", "部门": "市场部", "职位": "经理"},
  8.         {"姓名": "王五", "部门": "财务部", "职位": "会计"}
  9.     ],
  10.     "项目列表": [
  11.         {"项目": "数据平台", "状态": "进行中", "进度": "75%"},
  12.         {"项目": "移动应用", "状态": "已完成", "进度": "100%"},
  13.         {"项目": "AI模型", "状态": "规划中", "进度": "10%"}
  14.     ],
  15.     "设备清单": [
  16.         {"设备": "服务器A", "IP": "192.168.1.10", "状态": "运行中"},
  17.         {"设备": "服务器B", "IP": "192.168.1.11", "状态": "维护中"},
  18.         {"设备": "交换机", "IP": "192.168.1.1", "状态": "运行中"}
  19.     ]
  20. }
  21. document = Document()
  22. section = document.AddSection()
  23. doc_title = section.AddParagraph()
  24. doc_title_text = doc_title.AppendText("数据汇总报告")
  25. doc_title.Format.HorizontalAlignment = HorizontalAlignment.Center
  26. doc_title_text.CharacterFormat.Bold = True
  27. doc_title_text.CharacterFormat.FontSize = 22
  28. section.AddParagraph()
  29. for table_name, records in json_file_data.items():
  30.     # 每个表格的标题
  31.     table_title = section.AddParagraph()
  32.     table_title_text = table_title.AppendText(table_name)
  33.     table_title_text.CharacterFormat.Bold = True
  34.     table_title_text.CharacterFormat.FontSize = 14
  35.     section.AddParagraph()
  36.     headers = list(records[0].keys())
  37.     table = section.AddTable(True)
  38.     table.ResetCells(len(records) + 1, len(headers))
  39.     for i, header in enumerate(headers):
  40.         cell = table.Rows[0].Cells[i]
  41.         cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
  42.         cell.CellFormat.Shading.BackgroundPatternColor = Color.get_Gray()
  43.         paragraph = cell.AddParagraph()
  44.         paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
  45.         text_range = paragraph.AppendText(header)
  46.         text_range.CharacterFormat.Bold = True
  47.     for row_idx, record in enumerate(records):
  48.         for col_idx, key in enumerate(headers):
  49.             cell = table.Rows[row_idx + 1].Cells[col_idx]
  50.             cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
  51.             paragraph = cell.AddParagraph()
  52.             paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
  53.             paragraph.AppendText(str(record[key]))
  54.     table.ApplyStyle(DefaultTableStyle.ColorfulListAccent1)
  55.     table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)
  56.     section.AddParagraph()  # 表格间空行
  57. document.SaveToFile("JsonDataReport.docx", FileFormat.Docx)
  58. document.Close()
复制代码
实际使用 json.load() 从 .json 文件读取数据替换示例字典。AutoFitToWindow 让表格自适应页面宽度。

关键类与方法一览
- Document:Word 文档对象,支持创建、加载、保存。
- AddSection():添加节作为内容容器。
- AddTable():在节中创建表格。
- ResetCells(rows, cols):初始化表格行列。
- ApplyStyle(DefaultTableStyle.*):应用预设样式(如 ColorfulListAccent1、ColorfulGridAccent3)。
- ApplyVerticalMerge(column, startRow, endRow):垂直合并单元格。
- AutoFit(AutoFitBehaviorType.AutoFitToWindow):自动调整表格宽度。
- Rows/ Cells:行/列集合。
- CellFormat.Shading.BackgroundPatternColor:单元格背景色。
- CellFormat.VerticalAlignment:垂直对齐。
- AddParagraph() / AppendText():单元格或段落中添加文本。
- SaveToFile(path, FileFormat.Docx):保存为 .docx。

以上方法均可灵活组合,满足从简单段落到复杂嵌套表格的自动化生成需求。代码可直接用于 API 报告、配置文档、数据导出等场景。
回复

使用道具 举报

发表于 1 小时前 | 显示全部楼层

Re: Python 自动化:将 JSON 数据写入 Word 表格与段落(附代码)

感谢分享这个实用的教程!将 JSON 数据自动写入 Word 文档确实能极大提高工作效率,特别是对于需要向非技术人员展示结构化数据的场景。您提供的段落写入示例清晰易懂,表格部分虽然中断了,但思路已经展示出来,相信读者能很快理解核心逻辑。如果后续能补充完整表格生成代码以及处理嵌套数据的合并单元格示例,这篇教程会更有深度。期待更多类似的自动化技巧分享!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

指导单位

江苏省公安厅

江苏省通信管理局

浙江省台州刑侦支队

DEFCON GROUP 86025

Hacking Group 021A

旗下站点

态势感知中心

应急响应中心

红盟安全

联系我们

官方QQ群:112851260

官方邮箱:security#ihonker.org(#改成@)

官方核心成员

关注微信公众号

Archiver|手机版|小黑屋| ( 沪ICP备2021026908号 )

GMT+8, 2026-6-15 11:09 , Processed in 0.023559 second(s), 18 queries , Gzip On, Redis On.

Powered by ihonker.com

Copyright © 2015-现在.

  • 返回顶部