Skip to content

Instantly share code, notes, and snippets.

@kvendrik
Last active August 29, 2015 14:08
Show Gist options
  • Save kvendrik/e102f4877a9e5d37c9bd to your computer and use it in GitHub Desktop.
Save kvendrik/e102f4877a9e5d37c9bd to your computer and use it in GitHub Desktop.
Simple Excel to JSON converter
import xlrd
import json
import os.path
class ExcelToJson:
def convertFile(self, filePath, sheetName=None):
if not os.path.isfile(filePath):
print filePath+' does not exist or is not a file'
return
# make file path available to class
self.filePath = filePath
# open file and sheet
workbook = xlrd.open_workbook(filePath)
if sheetName is None:
sheet = workbook.sheet_by_index(0)
else:
sheet = workbook.sheet_by_name(sheetName)
# make sheet available to class
self.sheet = sheet
# contruct json
jsonArr = self._constructJson()
# save to file
self._writeJson(jsonArr)
print '---> Created '+filePath+'.json'
def _constructJson(self):
jsonArr = []
# loop rows
for rowIdx in range(1, self.sheet.nrows):
rowJson = self._getRowJson(rowIdx)
jsonArr.append(rowJson)
return jsonArr
def _getRowJson(self, rowIdx):
sheet = self.sheet
rowJson = {}
# loop columns
for colIdx in range(sheet.ncols):
colName = str(sheet.cell_value(0, colIdx))
rowVal = str(sheet.cell_value(rowIdx, colIdx))
rowJson.update({colName: rowVal})
return rowJson
def _writeJson(self, jsonArr):
# write to file
with open(self.filePath+'.json', "w") as jsonFile:
jsonFile.write(json.dumps(jsonArr))
import argparse
from exceltojson import ExcelToJson
def Main():
argParser = argparse.ArgumentParser(
description='Convert Excel sheet to JSON')
argParser.add_argument('filepath', type=str,
help='Path to excel file')
argParser.add_argument('--sheet', type=str,
help='Sheet to convert, defaults to first in file')
args = argParser.parse_args()
ExcelToJson().convertFile(args.filepath, args.sheet)
if __name__ == '__main__':
Main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment