#!/usr/local/bin/python
-- coding=utf-8 --
这段代码主要的功能是把excel表格转换成utf-8格式的lua文件
http://pypi.python.org/pypi/xlrd
import os
import xlrd
import warnings
import sys
from collections import OrderedDict
import codecs
import glob
reload(sys)
sys.setdefaultencoding(‘utf8’)
warnings.filterwarnings(“ignore”)
def excel2lua(excelPath, luaPath, filename):
wb = xlrd.open_workbook(excelPath)
convert_list = OrderedDict()
for i in range(0, wb.nsheets):
sh = wb.sheet_by_index(i)
print("\tread sheet %s, rows:%s"%(i, sh.nrows))
if (sh.nrows > 0):
#把excel的页读入OrderedDict
title = sh.row_values(0)
for rownum in range(1, sh.nrows):
rowvalue = sh.row_values(rownum)
single = OrderedDict()
for colnum in range(0, len(rowvalue)):
key = title[colnum]
if isinstance(key, float):
key = int(key)
value = rowvalue[colnum]
if isinstance(value, float):
value = int(value)
single[key] = value
convert_list[int(rowvalue[0])] = single
#写成lua格式
with codecs.open(luaPath, "w", "utf-8") as f:
f.write('local %s = {\n' % filename)
for row, rowdata in convert_list.items():
f.write(' [%d] = {' % row)
for col, coldata in rowdata.items():
if isinstance(coldata, int):
f.write('{0} = {1}, '.format(col, coldata))
else:
f.write('{0} = \"{1}\", '.format(col, coldata))
f.write('},\n')
f.write('}\n\nreturn ' + filename)
f.close()
print("create %s success!" % luaPath)
excelDir = ‘excel/’
luaDir = ‘lua/’
f = glob.glob(excelDir + ‘*.xlsx’)
for file in f :
filename = os.path.basename(os.path.splitext(file)[0])
print(filename + “.xlsx to lua…”)
excel2lua(’{0}{1}.xlsx’.format(excelDir, filename), ‘{0}{1}.lua’.format(luaDir, filename), filename)