平时使用excel较多,但是编程使用json格式较多,每次转换都很麻烦。所以写了一个小脚本。实现的思路很简单,利用xlrd操作excel,把表头作为字典的字段,逐行读取记录,其中数字python默认是float类型,此处写死强行换成str类型。最后利用Python的json包dumps一下,不过要注意ensure_ascii=False,不然会输出'/u989'之类的编码,indent = 2是为了输出的美观。
# -*- coding: utf-8 -*-
# 这段代码主要的功能是把excel表格转换成utf-8格式的json文件
import os
import sys
import codecs
import xlrd
import xdrlib
import json
reload(sys)
sys.setdefaultencoding( "utf-8" )
def open_ecxcel(file):
try:
data = xlrd.open_workbook(file)
return data
except Exception , e:
print str(e)
#根据名称获取Excel表格中的数据 参数:file:Excel文件路径 colnameindex:表头列名所在行的所以 ,by_name:Sheet1名称
def excel_table_byname(file,colnameindex=0,by_name=u'Sheet1'):
data = ope