Python進(jìn)行JSON和Excel文件轉(zhuǎn)換處理指南
在數(shù)據(jù)交換與系統(tǒng)集成中,JSON 與 Excel 是兩種極為常見的數(shù)據(jù)格式。JSON 適用于系統(tǒng)間傳輸,結(jié)構(gòu)靈活;而 Excel 更適合可視化展示與手動編輯。本文將介紹如何使用 Python 實現(xiàn) 將 JSON 轉(zhuǎn)換為格式化的 Excel 文件、從 Excel 生成 JSON 文件,并 處理嵌套 JSON 的扁平化問題,幫助你在多數(shù)據(jù)源場景下高效完成數(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 表格時,可以通過 Spire.XLS 自動寫入列頭與數(shù)據(jù),同時設(shè)置單元格樣式,使內(nèi)容更清晰易讀。
操作說明:
- 讀取 JSON 文件,提取鍵名作為表頭;
- 寫入數(shù)據(jù)并設(shè)置表頭樣式(加粗、背景色);
- 自動調(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()
# 自動調(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 時,可以自動讀取第一行作為鍵名,并逐行構(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)換
在實際開發(fā)中,JSON 數(shù)據(jù)經(jīng)常包含嵌套對象。若直接導(dǎo)入 Excel,結(jié)構(gòu)會混亂或不完整??墒褂帽馄交╢latten)技術(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àn) JSON 與 Excel 之間的相互轉(zhuǎn)換,滿足數(shù)據(jù)展示、系統(tǒng)交互等多種場景需求。對于結(jié)構(gòu)復(fù)雜的 JSON 數(shù)據(jù),也可通過自定義方法進(jìn)行處理,從而實現(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中的Descriptor描述符學(xué)習(xí)教程
簡單來說,數(shù)據(jù)描述符是指實現(xiàn)了__get__、__set__、__del__方法的類屬性,等效于定義了三個方法的接口,下面就來詳細(xì)看一下Python中的Descriptor修飾符學(xué)習(xí)教程2016-06-06
使用BeautifulSoup和Pandas進(jìn)行網(wǎng)頁數(shù)據(jù)抓取與清洗處理
在數(shù)據(jù)分析和機器學(xué)習(xí)的項目中,數(shù)據(jù)的獲取,清洗和處理是非常關(guān)鍵的步驟,下面我們就來講講如何利用Python中的Beautiful Soup庫進(jìn)行這樣的操作吧2025-02-02
python pyecharts 實現(xiàn)一個文件繪制多張圖
這篇文章主要介紹了python pyecharts 實現(xiàn)一個文件繪制多張圖,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
python 匿名函數(shù)與三元運算學(xué)習(xí)筆記
這篇文章主要介紹了python 匿名函數(shù)與三元運算的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)python 編程,感興趣的朋友可以了解下2020-10-10

