Python進(jìn)行JSON和Excel文件轉(zhuǎn)換處理指南
在數(shù)據(jù)交換與系統(tǒng)集成中,JSON 與 Excel 是兩種極為常見的數(shù)據(jù)格式。JSON 適用于系統(tǒng)間傳輸,結(jié)構(gòu)靈活;而 Excel 更適合可視化展示與手動(dòng)編輯。本文將介紹如何使用 Python 實(shí)現(xiàn) 將 JSON 轉(zhuǎn)換為格式化的 Excel 文件、從 Excel 生成 JSON 文件,并 處理嵌套 JSON 的扁平化問題,幫助你在多數(shù)據(jù)源場(chǎng)景下高效完成數(shù)據(jù)轉(zhuǎn)換。
本文使用的方法需要用到 Free Spire.XLS for Python,可通過pip安裝:pip install spire.xls.free。
將 JSON 導(dǎo)入為格式化 Excel
將結(jié)構(gòu)化 JSON 文件導(dǎo)入為 Excel 表格時(shí),可以通過 Spire.XLS 自動(dòng)寫入列頭與數(shù)據(jù),同時(shí)設(shè)置單元格樣式,使內(nèi)容更清晰易讀。
操作說明:
- 讀取 JSON 文件,提取鍵名作為表頭;
- 寫入數(shù)據(jù)并設(shè)置表頭樣式(加粗、背景色);
- 自動(dòng)調(diào)整列寬,提升可讀性;
- 保存為
.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 數(shù)據(jù)
with open("employees.json", "r", encoding="utf-8") as f:
data = json.load(f)
workbook = Workbook()
workbook.Worksheets.Clear()
sheet = workbook.Worksheets.Add("employees")
# 寫入表頭并設(shè)置樣式
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()
# 寫入數(shù)據(jù)并設(shè)置樣式
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()
# 自動(dòng)調(diào)整列寬
for i in range(1, len(headers) + 1):
sheet.AutoFitColumn(i)
# 保存 Excel 文件
workbook.SaveToFile("output/employees.xlsx", FileFormat.Version2016)
workbook.Dispose()生成的 Excel 文件截圖:

將 Excel 導(dǎo)出為結(jié)構(gòu)化 JSON
將 Excel 表格導(dǎo)出為 JSON 時(shí),可以自動(dòng)讀取第一行作為鍵名,并逐行構(gòu)造字典列表,最終保存為 .json 文件。
操作說明:
- 獲取最后一行和最后一列;
- 讀取第一行作為 headers;
- 逐行讀取數(shù)據(jù)并轉(zhuǎn)換為字典結(jié)構(gòu);
- 使用
json.dump輸出到文件。
代碼示例:
import json
# 獲取最大行列
rows = sheet.LastRow
cols = sheet.LastColumn
# 提取表頭
headers = [sheet.Range[1, i + 1].Text for i in range(cols)]
data = []
# 構(gòu)造 JSON 數(shù)據(jù)
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文件數(shù)據(jù):

生成的 JSON 文件片段:

處理嵌套 JSON:扁平化轉(zhuǎn)換
在實(shí)際開發(fā)中,JSON 數(shù)據(jù)經(jīng)常包含嵌套對(duì)象。若直接導(dǎo)入 Excel,結(jié)構(gòu)會(huì)混亂或不完整。可使用扁平化(flatten)技術(shù),將嵌套結(jié)構(gòu)展平為扁平鍵名形式(如 address.city)。
示例嵌套 JSON:
[
{
"name": "John",
"email": "john@example.com",
"address": {
"city": "New York",
"zip": "10001"
}
}
]Python 扁平化函數(shù)示例:
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
# 使用扁平化函數(shù)
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]扁平化后的結(jié)構(gòu):
[
{
"name": "John",
"email": "john@example.com",
"address.city": "New York",
"address.zip": "10001"
}
]總結(jié)
借助 Spire.XLS for Python,我們可以在 Python 項(xiàng)目中輕松實(shí)現(xiàn) JSON 與 Excel 之間的相互轉(zhuǎn)換,滿足數(shù)據(jù)展示、系統(tǒng)交互等多種場(chǎng)景需求。對(duì)于結(jié)構(gòu)復(fù)雜的 JSON 數(shù)據(jù),也可通過自定義方法進(jìn)行處理,從而實(shí)現(xiàn)高效的數(shù)據(jù)導(dǎo)入導(dǎo)出。
到此這篇關(guān)于Python進(jìn)行JSON和Excel文件轉(zhuǎn)換處理指南的文章就介紹到這了,更多相關(guān)Python JSON和Excel轉(zhuǎn)換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python3實(shí)現(xiàn)的Mysql數(shù)據(jù)庫操作封裝類
這篇文章主要介紹了Python3實(shí)現(xiàn)的Mysql數(shù)據(jù)庫操作封裝類,涉及Python針對(duì)mysql數(shù)據(jù)庫的連接、查詢、更新及關(guān)閉連接等相關(guān)操作技巧,需要的朋友可以參考下2018-06-06
Python標(biāo)準(zhǔn)庫之循環(huán)器(itertools)介紹
這篇文章主要介紹了Python標(biāo)準(zhǔn)庫之循環(huán)器(itertools)介紹,本文講解了無窮循環(huán)器、函數(shù)式工具、組合工具、groupby()、其它工具等內(nèi)容,需要的朋友可以參考下2014-11-11
python實(shí)現(xiàn)馬耳可夫鏈算法實(shí)例分析
這篇文章主要介紹了python實(shí)現(xiàn)馬耳可夫鏈算法的方法,實(shí)例分析了馬耳可夫鏈算法的原理與實(shí)現(xiàn)技巧,需要的朋友可以參考下2015-05-05
Django模板之基本的 for 循環(huán) 和 List內(nèi)容的顯示方式
這篇文章主要介紹了Django模板之基本的 for 循環(huán) 和 List內(nèi)容的顯示方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-03-03
python如何通過protobuf實(shí)現(xiàn)rpc
這篇文章主要為大家詳細(xì)介紹了python通過protobuf實(shí)現(xiàn)rpc的方法,感興趣的朋友可以參考一下2016-03-03
Python實(shí)現(xiàn)PS濾鏡碎片特效功能示例
這篇文章主要介紹了Python實(shí)現(xiàn)PS濾鏡碎片特效功能,結(jié)合實(shí)例形式分析了Python實(shí)現(xiàn)PS濾鏡碎片效果的具體步驟與相關(guān)操作技巧,需要的朋友可以參考下2018-01-01
Pycharm無法使用已經(jīng)安裝Selenium的解決方法
今天小編就為大家分享一篇Pycharm無法使用已經(jīng)安裝Selenium的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-10-10
Python實(shí)現(xiàn)讀寫INI配置文件的方法示例
這篇文章主要介紹了Python實(shí)現(xiàn)讀寫INI配置文件的方法,結(jié)合實(shí)例形式分析了Python針對(duì)ini配置文件的讀寫操作類定義及使用方法,需要的朋友可以參考下2018-06-06

