您的位置:首页 > 编程语言 > Lua

使用python把excel表格转换成lua配置表

2020-03-01 06:48 603 查看

#!/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)

  • 点赞
  • 收藏
  • 分享
  • 文章举报
baiqiuwangzi 发布了1 篇原创文章 · 获赞 0 · 访问量 169 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: