From ee8042c712bbe69cb5e17fe8e8e1770bf0a9424e Mon Sep 17 00:00:00 2001 From: Varun Tiwari Date: Mon, 10 Oct 2022 13:17:59 +0530 Subject: [PATCH] Added JSON to Excel converter --- scripts/json-to-excel/README.md | 13 ++++++++ scripts/json-to-excel/main.py | 54 +++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 scripts/json-to-excel/README.md create mode 100644 scripts/json-to-excel/main.py diff --git a/scripts/json-to-excel/README.md b/scripts/json-to-excel/README.md new file mode 100644 index 0000000..68864f6 --- /dev/null +++ b/scripts/json-to-excel/README.md @@ -0,0 +1,13 @@ +# JSON to Excel converter + +This is a simple Python script to convert a JSON file to an Excel file. + +## Usage + +```bash +# install xlwt +pip install xlwt + +# run script +python main.py +``` diff --git a/scripts/json-to-excel/main.py b/scripts/json-to-excel/main.py new file mode 100644 index 0000000..055aeaf --- /dev/null +++ b/scripts/json-to-excel/main.py @@ -0,0 +1,54 @@ +import json +import xlwt +import sys +import os +from collections import defaultdict + +if sys.argv[1] == "help": + print("Usage:\n\tjsonToExcel.py json_file.json") + sys.exit(1) + +if not os.path.exists(sys.argv[1]): + print("Cannot open " + sys.argv[1]) + sys.exit(1) + +file_name = sys.argv[1] +file_extenstion = file_name.split(".")[-1] + +if not file_extenstion in ("json"): + print("The extension of JSON file is incorrect") + sys.exit(1) + +file = open(file_name) +json_text = file.read() + +try: + imported_json = defaultdict(json.loads(json_text)) +except: + print("The content of the JSON file is incorrect") + sys.exit(1) + +workbook = xlwt.Workbook() +worksheet = workbook.add_sheet("json exported") + +columns = list(imported_json[0].keys()) + +i = 0 +for column in columns: + worksheet.write(0, i, column) + i += 1 + +j = 1 +for row in imported_json: + i = 0 + for column in columns: + worksheet.write(j, i, row[column]) + i += 1 + j += 1 + +try: + workbook.save(file_name.split(".")[0] + ".xls") + sys.exit(0) +except: + print("Cannot create the xls file") + sys.exit(1)