mirror of
https://github.com/metafy-social/python-scripts.git
synced 2024-11-27 14:01:12 +00:00
Merge pull request #308 from varunKT001/json-to-excel
Added JSON to Excel converter
This commit is contained in:
commit
3db555c936
13
scripts/json-to-excel/README.md
Normal file
13
scripts/json-to-excel/README.md
Normal file
|
@ -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 <JSON_FILE_PATH>
|
||||
```
|
54
scripts/json-to-excel/main.py
Normal file
54
scripts/json-to-excel/main.py
Normal file
|
@ -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)
|
Loading…
Reference in New Issue
Block a user