#!/usr/bin/env python
# -*- coding: utf-8 -*-
import xlrd
import json
import os
import sys
outPath = "./"
def readFromExcel(filepath):
dicts = {}
wr = xlrd.open_workbook(filepath)
# sheet1 = wr.sheet_names()[0]
sheet1 = wr.sheet_by_index(0) #获取第一个表格中的第一个sheet
rows = sheet1.nrows
cols = sheet1.ncols
print("--------",rows)
for i in range(1, rows):
key_row = str(sheet1.cell(i, 0).value)
# if key not in dicts:
dicts[key_row] = {}
for j in range(1, cols):
key_col = str(sheet1.cell(0, j).value)
dicts[key_row][key_col] = sheet1.cell(i, j).value.replace("\\n", "\n")
return dicts
def write_json(dicts, filename):
print("----------")
with open(filename, "w+") as fo:
fo.write(json.dumps(dicts, indent= 4, sort_keys=True, ensure_ascii=False))
if __name__ == '__main__':
if len(sys.argv) < 2:
print("not have dest file, please fill in")
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 = readFromExcel(filepath)
if dicts:
arr = filename.split("/")
excelname = arr[len(arr) - 1].split(".")[0] + ".json"
write_json(dicts, excelname)