Python Excel 转 JSON
代码:
import xlrd
import csv
def readFile(filePath):
try:
fileType = filePath.split(".")[-1]
print(f'{filePath}\t{fileType}')
if fileType == 'xlsx' or fileType=='xls':
res = []
wb = xlrd.open_workbook(filePath)
sh = wb.sheet_by_index(0)
title = []
for item in sh.row_values(0):
title.append(item)
data = []
[[data.append({title[index]: transfer(sh.row_values(it)[index]) for index in range(0,len(title))})] for it in range(1,sh.nrows)]
return data
elif fileType == "csv":
data = []
with open(filePath) as csvfile:
rows = csv.reader(csvfile)
title = next(rows)
[[data.append({title[index]: transfer(it[index]) for index in range(0, len(title))})] for it in rows]
return data
else:
return -1
except(EOFError):
print("转化过程出错!")
print(EOFError)
return -1
测试:
存为JSON
r = readFile(r''+os.path.join(BASE_DIR,"root","测试.xlsx"))
f = open("./测试.json",'wb',encoding='utf-8')
json.dump(f,r,ensure_ascii=False)
如果Excel中有中文的话,需要encoding='utf-8’和ensure_ascii=Fasle这两个配置,不然存入进去的就不是中文了。
|