Json2Excel.py3

本文介绍了一个使用Python编写的简单程序,该程序可以将JSON格式的数据转换为Excel文件。通过解析JSON数据并将其写入Excel表格中,此工具能够帮助用户更方便地管理和查看数据。支持复杂的JSON结构,并能正确处理包含转义字符的数据。
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import os
import sys
import xlwt
import xlrd
from xlutils.copy import copy

# json 格式 {"a" : {"a1": "a111", "a2": "a2222"}, "b" : {"b1": "b111", "b2": "b2222"}}

def write_excel(dicts, excelname):
    print("-------------", excelname)
    excelpath = os.path.join(os.getcwd(), excelname)

    #excel 不存在则创建
    if not os.path.isfile(excelpath):
        print("create excel file")
        wb = xlwt.Workbook(encoding = 'ascii')
        sheet1 = wb.add_sheet(u'sheet1', cell_overwrite_ok=True)
        wb.save(excelpath)
    # 读取excel 表
    rb = xlrd.open_workbook(excelpath)  #创建新的Excel(新的workbook),建议还是用ascii编码
    wb = copy(rb)
    # 获取第一个sheet开始写入
    sheet1 = wb.get_sheet(0)
    idxX = 0
    for key in dicts:
        idxX = idxX + 1
        # 写入竖向表头内容
        sheet1.write(idxX, 0, key)
        idxJ = 0
        for _k in dicts[key]:
            idxJ = idxJ + 1
            # 写入横向表头内容
            if idxX == 0:
                sheet1.write(0, idxJ, _k)
            # 写入加入转义
            dicts[key][_k] = dicts[key][_k].replace("\n", "\\n")
            # 写入表格内容
            sheet1.write(idxX, idxJ, dicts[key][_k])
    # 保存 excel 文件
    wb.save(excelpath)
    print('----save path ', excelpath)

    
def readDictsInfile(filepath):
    with open(filepath, "r", encoding="utf-8") as fo:
        dicts = json.load(fo)
    print(len(dicts))
    return dicts

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("not have argv[1] , please input your open JSON file")
        exit(0)
    filename = sys.argv[1]
    print("------filename", filename)
    filepath = os.path.join("./", filename)
    if not os.path.isfile(filepath):
        print("file is not exits")
        exit(0)
    else:
        dicts = readDictsInfile(filepath)
    if dicts:
        arr = filename.split("/")
        excelname = arr[len(arr) - 1].split(".")[0] + ".xls"
        write_excel(dicts, excelname)

 

Last login: Fri Jul 14 16:46:34 on ttys000 jeongyiii@Jeongyiii-2 ~ % cd Downloads jeongyiii@Jeongyiii-2 Downloads % python3 json2xml.py Traceback (most recent call last): File "json2xml.py", line 56, in <module> process_json_file(file_path) File "json2xml.py", line 50, in process_json_file dataframe_to_excel(expanded_df, excel_file_path) File "json2xml.py", line 32, in dataframe_to_excel writer.save() AttributeError: &#39;OpenpyxlWriter&#39; object has no attribute &#39;save&#39; jeongyiii@Jeongyiii-2 Downloads % vim json2xml.py jeongyiii@Jeongyiii-2 Downloads % python3 json2xml.py Excel file generated: example.xlsx jeongyiii@Jeongyiii-2 Downloads % python3 json2xml.py Excel file generated: example.xlsx jeongyiii@Jeongyiii-2 Downloads % python3 json2xml.py Excel file generated: example.xlsx jeongyiii@Jeongyiii-2 Downloads % vim json2xml.py jeongyiii@Jeongyiii-2 Downloads % python3 json2xml.py Excel file generated: example.xlsx jeongyiii@Jeongyiii-2 Downloads % python3 json2xml.py Excel file generated: example.xlsx jeongyiii@Jeongyiii-2 Downloads % vim json2xml.py jeongyiii@Jeongyiii-2 Downloads % vim json2xml.py def process_json_file(file_path): # Read JSON file json_data = read_json_file(file_path) # Parse JSON object json_obj = json.loads(json_data) # Convert JSON data to DataFrame df = json_to_dataframe(json_obj) # Expand the &#39;template&#39; column expanded_df = expand_template_column(df) # Write to Excel file excel_file_path = file_path.replace(&#39;.json&#39;, &#39;.xlsx&#39;) dataframe_to_excel(expanded_df, excel_file_path) print("Excel file generated:", excel_file_path) # Usage example file_path = &#39;example.json&#39; process_json_file(file_path) 说明
07-15
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值