平時(shí)使用excel較多懂版,但是編程使用json格式較多,每次轉(zhuǎn)換都很麻煩躏率。所以寫了一個(gè)小腳本躯畴。實(shí)現(xiàn)的思路很簡單,利用xlrd操作excel薇芝,把表頭作為字典的字段蓬抄,逐行讀取記錄,其中數(shù)字python默認(rèn)是float類型夯到,此處寫死強(qiáng)行換成str類型嚷缭。最后利用Python的json包dumps一下,不過要注意ensure_ascii=False
耍贾,不然會輸出'/u989'
之類的編碼阅爽,indent = 2
是為了輸出的美觀。
# -*- coding: utf-8 -*-
# 這段代碼主要的功能是把excel表格轉(zhuǎn)換成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)
#根據(jù)名稱獲取Excel表格中的數(shù)據(jù) 參數(shù):file:Excel文件路徑 colnameindex:表頭列名所在行的所以 荐开,by_name:Sheet1名稱
def excel_table_byname(file,colnameindex=0,by_name=u'Sheet1'):
data = open_ecxcel(file)
table = data.sheet_by_name(by_name)
nrows = table.nrows
colnames = table.row_values(colnameindex)
records = []
for rownum in range(1,nrows):
row = table.row_values(rownum)
if row:
record = {}
for i in range(len(colnames)):
#excel 默認(rèn)float ,強(qiáng)制類型轉(zhuǎn)換
if type(row[i]) == float:
row[i] = int(row[i])
row[i] = str(row[i])
record[colnames[i]] = row[i]
records.append(record)
return records
#open_ecxcel('wzsj.xlsx')
recodes = excel_table_byname('wzsj.xlsx')
encodedjson = json.dumps(recodes,ensure_ascii=False,indent=2)
#encodedjson = json.dumps(recodes)
print encodedjson
output = open('data11.json', 'w+')
output.write(encodedjson)
其中關(guān)于讀取excel數(shù)據(jù)還可以利用表格的索引值付翁,代碼如下
#根據(jù)索引獲取Excel表格中的數(shù)據(jù) 參數(shù):file:Excel文件路徑 colnameindex:表頭列名所在行的所以 ,by_index:表的索引
def excel_table_byindex(file,colnameindex=0,by_index=0):
data = open_ecxcel(file)
table = data.sheets()[by_index]
nrows = table.nrows #行數(shù)
ncols = table.ncols #列數(shù)
colnames = table.row_values(colnameindex) #某一行數(shù)據(jù)
records = []
for rownum in range(1,nrows):
row = table.row_values(rownum)
if row:
record = {}
for i in range(len(colnames)):
record[colnames[i]] = row[i]
records.append(record)
return records