Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
spreadsheet to json
#!/usr/bin/python
import os
import argparse
import xlrd
import json
def create_json_object(args):
workbook = xlrd.open_workbook(args.input)
sheet = workbook.sheet_by_index(0)
json_array = []
head_row = sheet.row(0)
for row_index in range(1, sheet.nrows):
json_dict = {}
row_values = sheet.row(row_index)
for col_index, col_value in enumerate(head_row):
json_dict[str(col_value.value)] = row_values[col_index].value
json_array.append(json_dict)
return {"Value": json_array}
def save_json(json_object, args):
with open(args.output, "w") as outfile:
if args.pretty:
json.dump(json_object, outfile, indent=4)
else:
json.dump(json_object, outfile)
def start():
parser = argparse.ArgumentParser(description="utility to convert a spreadsheet to a json collection of string dictionaries.")
parser.add_argument("-i", "--input", metavar="", required=True, help="the excel file to convert to json")
parser.add_argument("-o", "--output", metavar="", required=False, help="the file to wite the json to. if this is left blank json will be printed to the screen.")
parser.add_argument("-p", "--pretty", action="store_true", help="pretty print")
args = parser.parse_args()
json_object = create_json_object(args)
if args.output is None:
if args.pretty:
print(json.dumps(json_object, indent=4))
else:
print(json.dumps(json_object))
else:
save_json(json_object, args)
start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment