亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python進(jìn)行JSON和Excel文件轉(zhuǎn)換處理指南

 更新時(shí)間:2025年07月30日 15:34:58   作者:Eiceblue  
在數(shù)據(jù)交換與系統(tǒng)集成中,JSON 與 Excel 是兩種極為常見的數(shù)據(jù)格式,本文將介紹如何使用 Python 實(shí)現(xiàn) 將 JSON 轉(zhuǎn)換為格式化的 Excel 文件,從 Excel 生成 JSON 文件,希望對(duì)大家有所幫助

在數(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)容更清晰易讀。

操作說明:

  1. 讀取 JSON 文件,提取鍵名作為表頭;
  2. 寫入數(shù)據(jù)并設(shè)置表頭樣式(加粗、背景色);
  3. 自動(dòng)調(diào)整列寬,提升可讀性;
  4. 保存為 .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)文章

最新評(píng)論