在数据交换与系统集成中,json 与 excel 是两种极为常见的数据格式。json 适用于系统间传输,结构灵活;而 excel 更适合可视化展示与手动编辑。本文将介绍如何使用 python 实现 将 json 转换为格式化的 excel 文件、从 excel 生成 json 文件,并 处理嵌套 json 的扁平化问题,帮助你在多数据源场景下高效完成数据转换。
本文使用的方法需要用到 free spire.xls for python,可通过pip安装:pip install spire.xls.free。
将 json 导入为格式化 excel
将结构化 json 文件导入为 excel 表格时,可以通过 spire.xls 自动写入列头与数据,同时设置单元格样式,使内容更清晰易读。
操作说明:
- 读取 json 文件,提取键名作为表头;
- 写入数据并设置表头样式(加粗、背景色);
- 自动调整列宽,提升可读性;
- 保存为
.xlsx文件。
示例 json:employees.json
[
{"name": "alice", "age": 30, "department": "hr"},
{"name": "bob", "age": 27, "department": "it"},
{"name": "charlie", "age": 35, "department": "sales"}
]代码示例:
from spire.xls import workbook, fileformat, color
import json
# 加载 json 数据
with open("employees.json", "r", encoding="utf-8") as f:
data = json.load(f)
workbook = workbook()
workbook.worksheets.clear()
sheet = workbook.worksheets.add("employees")
# 写入表头并设置样式
headers = list(data[0].keys())
for col, header in enumerate(headers):
cell = sheet.range[1, col + 1]
cell.text = header
cell.style.font.fontname = "times new roman"
cell.style.font.isbold = true
cell.style.font.size = 16.0
cell.style.color = color.get_lightgray()
# 写入数据并设置样式
for row_idx, row in enumerate(data, start=2):
for col_idx, key in enumerate(headers):
sheet.range[row_idx, col_idx + 1].text = str(row.get(key, ""))
datarange = sheet.range[2, 1, sheet.lastrow, sheet.lastcolumn]
datarange.style.color = color.get_lightpink()
datarange.style.font.fontname = "arial"
datarange.style.font.size = 12.0
datarange.borderinside()
datarange.borderaround()
# 自动调整列宽
for i in range(1, len(headers) + 1):
sheet.autofitcolumn(i)
# 保存 excel 文件
workbook.savetofile("output/employees.xlsx", fileformat.version2016)
workbook.dispose()生成的 excel 文件截图:

将 excel 导出为结构化 json
将 excel 表格导出为 json 时,可以自动读取第一行作为键名,并逐行构造字典列表,最终保存为 .json 文件。
操作说明:
- 获取最后一行和最后一列;
- 读取第一行作为 headers;
- 逐行读取数据并转换为字典结构;
- 使用
json.dump输出到文件。
代码示例:
import json
# 获取最大行列
rows = sheet.lastrow
cols = sheet.lastcolumn
# 提取表头
headers = [sheet.range[1, i + 1].text for i in range(cols)]
data = []
# 构造 json 数据
for r in range(2, rows + 1):
row_data = {}
for c in range(cols):
row_data[headers[c]] = sheet.range[r, c + 1].text
data.append(row_data)
# 输出 json 文件
with open("output/products_out.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=false)excel文件数据:

生成的 json 文件片段:

处理嵌套 json:扁平化转换
在实际开发中,json 数据经常包含嵌套对象。若直接导入 excel,结构会混乱或不完整。可使用扁平化(flatten)技术,将嵌套结构展平为扁平键名形式(如 address.city)。
示例嵌套 json:
[
{
"name": "john",
"email": "john@example.com",
"address": {
"city": "new york",
"zip": "10001"
}
}
]python 扁平化函数示例:
def flatten_json(obj, prefix=""):
flat = {}
for key, value in obj.items():
full_key = f"{prefix}{key}" if prefix == "" else f"{prefix}.{key}"
if isinstance(value, dict):
flat.update(flatten_json(value, full_key))
else:
flat[full_key] = value
return flat
# 使用扁平化函数
with open("nested.json", "r", encoding="utf-8") as f:
nested_data = json.load(f)
flat_data = [flatten_json(item) for item in nested_data]扁平化后的结构:
[
{
"name": "john",
"email": "john@example.com",
"address.city": "new york",
"address.zip": "10001"
}
]总结
借助 spire.xls for python,我们可以在 python 项目中轻松实现 json 与 excel 之间的相互转换,满足数据展示、系统交互等多种场景需求。对于结构复杂的 json 数据,也可通过自定义方法进行处理,从而实现高效的数据导入导出。
到此这篇关于python进行json和excel文件转换处理指南的文章就介绍到这了,更多相关python json和excel转换内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论