您的位置:首页 > 移动开发 > Unity3D

excel导出csv

2015-06-15 15:50 441 查看
脚本:python

插件:xlrd

约定:前三行为配置信息,依次为变量名、数据类型、描述信息(这些配置主要是为了以后批量生成代码时使用)

脚本代码如下:

#!-*- coding:utf-8 -*-
#
#	excel转csv
#

import xlrd,csv,sys,os,shutil

class E2CParser(object):
"""docstring for ClassName"""
def __init__(self, excelfile):
super(E2CParser, self).__init__()
self.filename = excelfile

def parser(self):
print "开始解析  : %s" % self.filename

if not os.path.exists('csv'):
os.mkdir('csv')
pass

workbook = xlrd.open_workbook(self.filename)
sheet = workbook.sheet_by_index(0)
ext = os.path.splitext( os.path.basename(self.filename) )
# print ext

with open('./csv/{}.csv'.format(ext[0]), 'wb') as f:
writer = csv.writer(f,delimiter="\t")

for row in range(3,sheet.nrows):
out=[]
for index,cell in enumerate(sheet.row_values(row)):
__type__ = sheet.cell(2,index).value.lower()
try:
if __type__ == 'int':
out.append( unicode( int(cell) ).encode('utf-8') )
elif __type__ == 'array_int' and type(value) is float:
out.append( unicode( int(cell) ).encode('utf-8') )
else:
out.append(unicode(cell).encode('utf-8'))
except Exception,e:
print "(%d , %d) data is error!" % (row+1,index+1)
if __type__ == 'int' or __type__ == 'array_int':
out.append( unicode( 0 ).encode('utf-8') )
else:
out.append(unicode('-1').encode('utf-8'))

writer.writerow(out)
print "Parser Success!"

#
#	遍历目录下的所有带有excel后缀的文件
#
def readExcel(path):
path = os.path.normpath(path)
# print path
if os.path.exists(path):
if os.path.isdir(path):
for _file in os.listdir(path):
readExcel(os.path.join(path,_file))
elif os.path.isfile(path):
ext = os.path.splitext(path)
if ext[1] in ['.xls','.xlsx']:
obj = E2CParser(path)
obj.parser()
else:
print "不存在路径 : "+path

if __name__ == '__main__':
if os.path.exists("csv"):
shutil.rmtree("csv")
readExcel('excel')


当前脚本只解析excel目录下的文件,
readExcel('excel')


当然你也可以通过命令行参数,来解析特定的文件夹或文件:

opts,args = getopt.getopt(args, shortopts, longopts = [])
这样你就取到了参数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  excel csv unity