专职C++

不能停止的脚步

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  163 Posts :: 7 Stories :: 135 Comments :: 0 Trackbacks

常用链接

留言簿(28)

我参与的团队

搜索

  •  

最新评论

阅读排行榜

评论排行榜

    在游戏开发过程中,游戏配置更新是很常的事情。其中一个主要的方法,是用excel来进行游戏配表。然后导出,可以导出前台和后台的配置,这样策划就不用针对前后台,分别给配置了。在这里,python就有大作用了。通过以前的积累,这里给出一个目前我这里使用的最新的,希望能给大家有所帮助。
我这里配置,支持.conf(ini格式),.csv,.jsn和.mall或.js(json格式),.cfg(我这里定义的一种数据格式和对应的ActionScript代码),还有.sql和.key格式。并支持最新的excel 2013的表格。(这个是由第三方库提供的)。
    首先,在excel表格中,要有一个表名tablelist,这个表格用来描述导出哪些配置。这个表的主要的字段有“表名,说明,输出文件名,输出的字段,输出的类名,查询的Key”,其中是应用于.cfg格式。
表名:指对应的excel表格的名称。
说明:描述这个导出配置是做什么用的。
输出文件名:输出的配置文件名。
输出的字段:输出excel中的表格中字段
输出的类名:如果是.cfg格式的数据,这里需要提供输出ActionScript类的名称,其他格式无视
查询的Key:如果是.cfg格式的数据,这里可以定义一组查询的Key字段,这样在ActionScript中,会生成一个查询的函数
    其次:excel一个有用的公式:=IF(F2<>"",CONCATENATE("[",VLOOKUP(F2,Props!A:B,2,FALSE),",",G2,"]"),"[0,0]"),通过VLOOKUP查询Props表的A到B列,输出第二列。这样策划只要要查询的名称不后,后面对应的数据,变化,整个配置表的数据,会做同步变化,如下图

      这里使用的第三方python库是xlrd,下载地址是# http://pypi.python.org/pypi/xlrd
      在python源文件的开头,要加上
#!/usr/bin/python
# -*- coding: utf-8 -*-
不然写代码中有中文的时候,就会有错误!
下面给出一个实际的tablelist截图:

下面给出一个等级表的例子截图:

这样以后,就可以用了。下面,这里给出完整的python代码
#!/usr/bin/python
#
 -*- coding: utf-8 -*-
#
 这段代码主要的功能是把excel表格转换成utf-8格式的json文件
#
 lastdate:2011-8-15 14:21 version 1.1 

import os
import sys
import codecs
import xlrd  # http://pypi.python.org/pypi/xlrd

RefClassList = []
strPackageName = u"com.hxgd.cfg";

def FloatToString (aFloat):
    if type(aFloat) != float:
        return ""
    strTemp = str(aFloat)
    strList = strTemp.split(".")
    if len(strList) == 1 :
        return strTemp
    else:
        if strList[1] == "0" :
            return strList[0]
        else:
            return strTemp

# 查找第1个非要求的字符串的下标
def findFirstNot(paramString, paramBegin, paramSubstr):
    for i in range(paramBegin, len(paramString)):
        if paramSubstr.find(paramString[i]) == -1:
            return i
    return -1

# 解析filter字符串,返回变量数组
def parseFilterKey(paramFilter):
    ret = []
    begin = 0
    while True:
        index = paramFilter.find("$", begin)
        if index >= 0:
            index += 1
            end = findFirstNot(paramFilter, index, "1234567890abcdefghijklmnopqrstuvwxyz_ABC DEFGHIJKLMNOPQRSTUVWXYZ")
            key = paramFilter[index:end]
            ret.append(key)
            begin = end
        else:
            return ret

# 读入字段映射表
def readMap(paramTable):
    mapTable = {}
    nrow = paramTable.nrows
    if paramTable.ncols == 0:
        return mapTable

    for r in range(nrow):
        k = paramTable.cell_value(r, 0)
        if paramTable.ncols < 2:
            v = k
        else:
            v = paramTable.cell_value(r, 1)
            if (len(v) == 0):
                v = k
        mapTable[k] = v
    return mapTable

# 读取字段列表
def readFieldMap(paramFields):
    mapField = {}
    strList = paramFields.split(",")
    for f in strList:
        mapField[f] = f
    return mapField

#            table2as3config(destTable, destFileName, mapTable, mapParam)

def CellToString(paramCell):
    strCellValue = u""
    if type(paramCell) == unicode:
        strCellValue = paramCell
    elif type(paramCell) == float:
        strCellValue = FloatToString(paramCell)
    else:
        strCellValue = str(paramCell)
    return strCellValue

def table2as3config(paramTable, paramDestFileName, paramUseFields, paramClassName, paramKeyMap):
    nrows = paramTable.nrows
    ncols = paramTable.ncols
    col_index_list = range(ncols)

    title_map_to_index = {}
    field_flag = [["", False, 0] for i in col_index_list]
    
    use_field_index = []        

    for index in col_index_list:
        field_name = paramTable.cell_value(0, index)
        strTitle = field_name.replace(u"\n", u"").replace(u"\"", u"")  # 取出引号和\n这样的字符
        field_flag[index][0] = strTitle
        if (field_name.rfind(u"\"") >= 0):
            field_flag[index][1] = True
            field_flag[index][2] = 1
        title_map_to_index[strTitle] = index  # 得到字段名对应的下标

    for use_field in paramUseFields:
        if use_field in title_map_to_index:
            use_field_index.append(title_map_to_index[use_field])
    # 生成类名
    strClassName = u"[" + paramClassName + u"]\r\n";
    # 生成字段列表
    strFieldList = u"<";
    field_count = len(use_field_index)
    if field_count > 0:
        for i in range(field_count - 1):
            strFieldList += field_flag[use_field_index[i]][0]
            strFieldList += ","
        strFieldList += field_flag[use_field_index[field_count - 1]][0]
    strFieldList += ">\r\n"

    # 输出配置
    objDir = os.path.dirname(paramDestFileName)
    if objDir and not os.path.exists(objDir):
        os.makedirs(objDir)    
    f = codecs.open(paramDestFileName, "w""utf-8")
    f.write(strClassName)
    f.write(strFieldList)

    for i in range(field_count):
        col_index = use_field_index[i]
        strCell = CellToString(paramTable.cell_value(1, col_index))
        print (u"[1,", i, u"]=", strCell)
        if len(strCell) > 0:
            chFirst = strCell[0]
            if chFirst == u'[':
                field_flag[col_index][2] = 2
    
    for r in range(1, nrows):
        strTmp = u"#"
        if field_count < 1:
            continue
        for i in range(field_count - 1):
            col_index = use_field_index[i]
            strCell = CellToString(paramTable.cell_value(r, col_index))
            if field_flag[col_index][1]:
                strTmp += u"\"" + strCell + u"\""
            else:
                strTmp += strCell
            strTmp += u","
#            if r == 1:
#
                print (u"[", r,u",",i, u"]=",strCell)
#
                chFirst = strCell[0]
#
                if chFirst == u'[':
#
                    field_flag[col_index][2]=2
        col_index = use_field_index[field_count - 1]
        strCell = CellToString(paramTable.cell_value(r, col_index))
        if field_flag[col_index][1]:
            strTmp += u"\"" + strCell + u"\""
        else:
            strTmp += str(strCell)
        strTmp += u"\r\n"
        f.write(strTmp);
    f.close()
    # 生成类
    
    
    strClassName = paramClassName
    RefClassList[len(RefClassList):] = [strClassName]
    as3 = codecs.open("./" + strClassName + u".as""w""utf-8")
    as3.write(u"package " + strPackageName + u"\n")
    as3.write(u"{\n")
    as3.write(u"    public class " + strClassName + u" extends ConfigBase\n")
    as3.write(u"    {\n")
    as3.write(u"        public function " + strClassName + u"()\n")
    as3.write(u"        {\n")
    as3.write(u"            super();\n")
    as3.write(u"        }\n\n")
    as3.write(u"        public static var List:Array = [];\n\n")
    as3.write(u"        public static function AddRecord(paramRecord:Array):void\n")
    as3.write(u"        {\n")
    as3.write(u"            var r:" + strClassName + u" = new " + strClassName + u"();\n")
    as3.write(u"            r.DoLoad(paramRecord);\n")
    as3.write(u"            List.push(r);\n")
    as3.write(u"        }\n\n")
    print("paramKeyMap:", paramKeyMap)
    for map_key in paramKeyMap:
        print("map_key:" + map_key)
        as3.write(u"        public static function GetBy_" + map_key + "(paramKey:*):" + strClassName + "\n")
        as3.write(u"        {\n")
        as3.write(u"            for each (var record:" + strClassName + " in List)\n")
        as3.write(u"            {\n")
        as3.write(u"                if (record." + map_key + " == paramKey)\n")
        as3.write(u"                {\n")
        as3.write(u"                    return record;\n")
        as3.write(u"                }\n")
        as3.write(u"            }\n")
        as3.write(u"            return null;\n")
        as3.write(u"        }\n\n")

    as3.write(u"        override public function DoLoad(paramRecord:Array):void\n        {\n")
    for i in range(field_count):
        col_index = use_field_index[i]
        strFieldName = field_flag[col_index][0]
        as3.write(u"            " + strFieldName + u" = paramRecord[" + str(i) + u"];\n")
    as3.write(u"        }\n\n")

    for i in range(field_count):
        col_index = use_field_index[i]
        strFieldName = field_flag[col_index][0]
        iFlag = field_flag[col_index][2]
        if iFlag == 0:
            as3.write(u"        public var " + strFieldName + u":Number;\n")
        elif iFlag == 1:
            as3.write(u"        public var " + strFieldName + u":String;\n")
        elif iFlag == 2:
            as3.write(u"        public var " + strFieldName + u":Array=[];\n")
    as3.write(u"    }\n}\n")
    as3.close();
    print "Create ", paramDestFileName, " OK"
    return



def table2jsn(table, jsonfilename, mapTable, mapParam):
# {"name":"数组名", "var":"变量名", "index1":True, "filter":"$Online>0 and $Name=='加速锦囊(1小时)'"}
    nrows = table.nrows
    ncols = table.ncols
    hasMap = (len(mapTable) > 0)
    objDir = os.path.dirname(jsonfilename)
    if objDir and not os.path.exists(objDir):
        os.makedirs(objDir)    
    f = codecs.open(jsonfilename, "w""utf-8")
    strTmp = u""
    
    # 解析filter字符串
    filterKey = []
    filterString = ""
    if "filter" in mapParam and len(mapParam["filter"]) > 0:
        filterString = mapParam["filter"].decode("utf8")
        filterKey = parseFilterKey(filterString)

    # var xxx = 
    if ("var" in mapParam) and (len(mapParam["var"]) > 0):
        strTmp += u"var " + mapParam["var"] + u" = "

    # name:[
    if "name" in mapParam:
        if (len(mapParam["name"]) > 0):
            strTmp += u"{\n\t\"" + mapParam["name"] + "\":"
    else:
        strTmp += u"{\n\t\"list\":"

    if len(strTmp) == 0:  # 此时加个\t使前后对齐
        strTmp += u"\t[\n"
    else:
        strTmp += u"[\n"

    if ("index1" in mapParam) and (mapParam["index1"]):
        strTmp += u"\t\t{},\n"
    f.write(strTmp)
    rs = 0
    for r in range(1, nrows):
        strTmp = u"\t\t{ "
        i = 0
        strFilter = filterString
        skip_row = False
        get_this = not (len(filterKey) > 0)
        for c in range(ncols):
            title = table.cell_value(0, c)
            isString = (title.rfind(u"\"") >= 0)
            title = title.replace(u"\n", u"").replace(u"\"", u"")

            if hasMap:
                if not title in mapTable:
                    continue
                else:
                    title = mapTable[title]

            strCellValue = u""
            CellObj = table.cell_value(r, c)
            if type(CellObj) == unicode:
                strCellValue = CellObj
            elif type(CellObj) == float:
                strCellValue = FloatToString(CellObj)
            else:
                strCellValue = str(CellObj)

            if isString:
                strCellValue = strCellValue.replace(u"\n", u"").replace(u"\"", u"")

            if not get_this and title in filterKey:
                if isString:
                    strFilter = strFilter.replace(u"$" + title, u"\"" + strCellValue + u"\"")
                else:
                    strFilter = strFilter.replace(u"$" + title, strCellValue)

                if strFilter.find("$") == -1:
                    if not eval(strFilter):  # 被过滤了
                        skip_row = True
                        break
                    else:
                        get_this = True  # 确定了这行要

            if i > 0:
                delm = u""
            else:
                delm = u""

            if isString:
                strTmp += delm + u"\"" + title + u"\":\"" + strCellValue + u"\""
            else:
                strTmp += delm + u"\"" + title + u"\":" + strCellValue
            i += 1
        
        if skip_row:  # 被过滤了
            continue
        
        strTmp += u" }"
        if rs > 0:  # 不是第1行
            f.write(u",\n")
        f.write(strTmp)
        rs += 1

    strTmp = u"\n\t]"
    if "name" in mapParam:
        if (len(mapParam["name"]) > 0):
            strTmp += u"\n}"
    else:
        strTmp += u"\n}"

    strTmp += u"\n"
    f.write(strTmp)
    f.close()
    print "Create ", jsonfilename, " OK"
    return


def table2mall(table, jsonfilename, mapTable, mapParam):
# {"name":"数组名", "var":"变量名", "index1":True, "filter":"$Online>0 and $Name=='加速锦囊(1小时)'"}
    nrows = table.nrows
    ncols = table.ncols
    hasMap = (len(mapTable) > 0)
    objDir = os.path.dirname(jsonfilename)
    if objDir and not os.path.exists(objDir):
        os.makedirs(objDir)    
    f = codecs.open(jsonfilename, "w""utf-8")
    strTmp = u""
    
    # 解析filter字符串
    filterKey = []
    filterString = ""
    if "filter" in mapParam and len(mapParam["filter"]) > 0:
        filterString = mapParam["filter"].decode("utf8")
        filterKey = parseFilterKey(filterString)

    # var xxx = 
    if ("var" in mapParam) and (len(mapParam["var"]) > 0):
        strTmp += u"var " + mapParam["var"] + u" = "

    # name:[
    if "name" in mapParam:
        if (len(mapParam["name"]) > 0):
            strTmp += u"{\n\t\"" + mapParam["name"] + "\":"
    else:
        strTmp += u"{\n\t\"list\":"

    if len(strTmp) == 0:  # 此时加个\t使前后对齐
        strTmp += u"\t[\n"
    else:
        strTmp += u"[\n"

    if ("index1" in mapParam) and (mapParam["index1"]):
        strTmp += u"\t\t{},\n"
    f.write(strTmp)
    rs = 0
    for r in range(1, nrows):
        strTmp = u"\t\t{ "
        i = 0
        strFilter = filterString
        skip_row = False
        get_this = not (len(filterKey) > 0)
        for c in range(ncols):
            title = table.cell_value(0, c)
            isString = (title.rfind(u"\"") >= 0)
            title = title.replace(u"\n", u"").replace(u"\"", u"")

            if hasMap:
                if not title in mapTable:
                    continue
                else:
                    title = mapTable[title]

            strCellValue = u""
            CellObj = table.cell_value(r, c)
            if type(CellObj) == unicode:
                strCellValue = CellObj
            elif type(CellObj) == float:
                strCellValue = FloatToString(CellObj)
            else:
                strCellValue = str(CellObj)

            if isString:
                strCellValue = strCellValue.replace(u"\n", u"").replace(u"\"", u"")

            if not get_this and title in filterKey:
                if isString:
                    strFilter = strFilter.replace(u"$" + title, u"\"" + strCellValue + u"\"")
                else:
                    strFilter = strFilter.replace(u"$" + title, strCellValue)

                if strFilter.find("$") == -1:
                    if not eval(strFilter):  # 被过滤了
                        skip_row = True
                        break
                    else:
                        get_this = True  # 确定了这行要

            if i > 0:
                delm = u""
            else:
                delm = u""

            if isString:
                strTmp += delm + u"\"" + title + u"\":\"" + strCellValue + u"\""
            else:
                strTmp += delm + u"\"" + title + u"\":" + strCellValue
            i += 1
        
        if skip_row:  # 被过滤了
            continue
        
        strTmp += u" }"
        if rs > 0:  # 不是第1行
            f.write(u",\n")
        f.write(strTmp)
        rs += 1

    strTmp = u"\n\t]"
    if "name" in mapParam:
        if (len(mapParam["name"]) > 0):
            strTmp += u"\n}"
    else:
        strTmp += u"\n}"

    strTmp += u"\n"
    f.write(strTmp)
    f.close()
    print "Create ", jsonfilename, " OK"
    return

def table2sql(table, jsonfilename, mapTable, mapParam):
# {"name":"表名", "delete":False, "commit":True, "filter":"$Online>0 and $Name=='加速锦囊(1小时)'"}
    nrows = table.nrows
    ncols = table.ncols
    hasMap = (len(mapTable) > 0)
    objDir = os.path.dirname(jsonfilename)
    if objDir and not os.path.exists(objDir):
        os.makedirs(objDir)

    # 解析filter字符串
    filterKey = []
    filterString = ""
    if "filter" in mapParam and len(mapParam["filter"]) > 0:
        filterString = mapParam["filter"].decode("utf8")
        filterKey = parseFilterKey(filterString)

    tablename = destFileName[:destFileName.rfind(".")]  # 用文件名做表名
    tablename = tablename[tablename.rfind("\\") + 1:]
    if ("name" in mapParam) and len(mapParam["name"]) > 0:
        tablename = mapParam["name"]

    f = codecs.open(jsonfilename, "w""utf-8")
    if not ("delete" in mapParam and not mapParam["delete"]):
        f.write(u"truncate table " + tablename + u";\n")
    f.write(u"set names 'utf8';\n")

    if not(("commit" in mapParam) and not mapParam["commit"]):
        f.write(u"set autocommit=0;\n")

    for r in range(1, nrows):
        strTmp = u"insert into " + tablename + " set "
        i = 0
        strFilter = filterString
        skip_row = False
        get_this = not (len(filterKey) > 0)
        for c in range(ncols):
            title = table.cell_value(0, c)
            isString = (title.rfind(u"\"") >= 0)
            title = title.replace(u"\n", u"").replace(u"\"", u"")

            if hasMap:
                if not title in mapTable:
                    continue
                else:
                    title = mapTable[title]

            strCellValue = u""
            CellObj = table.cell_value(r, c)
            if type(CellObj) == unicode:
                strCellValue = CellObj
            elif type(CellObj) == float:
                strCellValue = FloatToString(CellObj)
            else:
                strCellValue = str(CellObj)
            
            if isString:
                strCellValue = strCellValue.replace(u"\n", u"").replace(u"'", u"\"")

            if not get_this and title in filterKey:
                if isString:
                    strFilter = strFilter.replace(u"$" + title, u"\"" + strCellValue + u"\"")
                else:
                    strFilter = strFilter.replace(u"$" + title, strCellValue)

                if strFilter.find("$") == -1:
                    if not eval(strFilter):  # 被过滤了
                        skip_row = True
                        break
                    else:
                        get_this = True  # 确定了这行要

            if i > 0:
                delm = u""
            else:
                delm = u""

            if isString:
                strTmp += delm + title + u" = '" + strCellValue + u"'"
            else:
                strTmp += delm + title + u" = " + strCellValue
            i += 1

        if skip_row:  # 被过滤了
            continue

        strTmp += u";\n"
        f.write(strTmp)

    if not(("commit" in mapParam) and not mapParam["commit"]):
        f.write(u"commit;\n")
    f.write(u"\n")
    f.close()
    print "Create ", jsonfilename, " OK"
    return

def table2ini(table, inifilename, mapTable, mapParam):
# {"name":"section名", "filter":"$Online>0 and $Name=='加速锦囊(1小时)'"}
    nrows = table.nrows
    ncols = table.ncols
    hasMap = (len(mapTable) > 0)
    objDir = os.path.dirname(inifilename)
    if objDir and not os.path.exists(objDir):
        os.makedirs(objDir)
        
    # 解析filter字符串
    filterKey = []
    filterString = ""
    if "filter" in mapParam and len(mapParam["filter"]) > 0:
        filterString = mapParam["filter"].decode("utf8")
        filterKey = parseFilterKey(filterString)

    section = destFileName[:destFileName.rfind(".")]  # 用文件名做节名
    section = section[section.rfind("\\") + 1:]
    if ("name" in mapParam) and len(mapParam["name"]) > 0:
        section = mapParam["name"]

    f = codecs.open(inifilename, "w""utf-8")
    rs = 1
    for r in range(1, nrows):
        strTmp = u"[" + section + str(rs) + u"]\n"
        strFilter = filterString
        skip_row = False
        get_this = not (len(filterKey) > 0)
        
        for c in range(ncols):
            title = table.cell_value(0, c)
            isString = (title.rfind(u"\"") >= 0)
            title = title.replace(u"\n", u"").replace(u"\"", u"")

            if hasMap:
                if not title in mapTable:
                    continue
                else:
                    title = mapTable[title]

            strCellValue = u""
            CellObj = table.cell_value(r, c)
            if type(CellObj) == unicode:
                strCellValue = CellObj
            elif type(CellObj) == float:
                strCellValue = FloatToString(CellObj)
            else:
                strCellValue = str(CellObj)

            strCellValue = strCellValue.replace(u"\n", u"")  # 去掉换行
            if not get_this and title in filterKey:
                if isString:
                    strFilter = strFilter.replace(u"$" + title, u"\"" + strCellValue.replace(u"\"", u"") + u"\"")
                else:
                    strFilter = strFilter.replace(u"$" + title, strCellValue)

                if strFilter.find("$") == -1:
                    if not eval(strFilter):  # 被过滤了
                        skip_row = True
                        break
                    else:
                        get_this = True  # 确定了这行要

            strTmp += title + u" = " + strCellValue + "\n"

        if skip_row:  # 被过滤了
            continue

        rs += 1
        strTmp += u"\n"
        f.write(strTmp)

    strTmp = u"[" + section + u"]\n"
    strTmp += u"Count = " + str(rs - 1) + u"\n"
    f.write(strTmp)

    f.close()
    print "Create ", inifilename, " OK"
    return

def table2csv(table, csvfilename, mapTable, mapParam):
# {"title":False, "filter":"$Online>0 and $Name=='加速锦囊(1小时)'"}
    nrows = table.nrows
    ncols = table.ncols
    hasMap = (len(mapTable) > 0)
    objDir = os.path.dirname(csvfilename)
    if objDir and not os.path.exists(objDir):
        os.makedirs(objDir)
    f = codecs.open(csvfilename, "w""utf-8")
    
    # 解析filter字符串
    filterKey = []
    filterString = ""
    if "filter" in mapParam and len(mapParam["filter"]) > 0:
        filterString = mapParam["filter"].decode("utf8")
        filterKey = parseFilterKey(filterString)

    for r in range(nrows):
        i = 0
        strFilter = filterString
        skip_row = False
        get_this = not (len(filterKey) > 0)
        strTmp = u""

        if r == 0 and ("title" in mapParam) and not (mapParam["title"]):
            print("#########################################")
            continue

        for c in range(ncols):
            title = table.cell_value(0, c)
            isString = (title.rfind(u"\"") >= 0)
            title = title.replace(u"\n", u"").replace(u"\"", u"").replace(u",", u"")

            if hasMap:
                if not title in mapTable:
                    continue
                else:
                    title = mapTable[title]

            if i > 0:
                delm = u","
            else:
                delm = u""

            if r == 0:  # 第一行不同
                strTmp += delm + title
            else:
                strCellValue = u""
                CellObj = table.cell_value(r, c)
                if type(CellObj) == unicode:
                    strCellValue = CellObj.replace(u"\n", u"")  # .replace(u",", u"")
                elif type(CellObj) == float:
                    strCellValue = FloatToString(CellObj)
                else:
                    strCellValue = str(CellObj).replace(u"\n", u"").replace(u",", u"")

                if not get_this and title in filterKey:
                    if isString:
                        strFilter = strFilter.replace(u"$" + title, u"\"" + strCellValue.replace(u"\"", u"") + u"\"")
                    else:
                        strFilter = strFilter.replace(u"$" + title, strCellValue)

                    if strFilter.find("$") == -1:
                        if not eval(strFilter):  # 被过滤了
                            skip_row = True
                            break
                        else:
                            get_this = True  # 确定了这行要

                strTmp += delm + strCellValue
            i += 1

        if skip_row:  # 被过滤了
            continue

        strTmp += u"\n"
        f.write(strTmp)
    f.close()
    print "Create ", csvfilename, " OK"
    return

#   RefClassList[1:] = [strClassName]
#
    as3 = codecs.open("./"+strClassName+u".as","w","utf-8")
#
    as3.write(u"package " + strPackageName + u"\n")

def create_ref():
    as3 = codecs.open(u"./ClassRef.as""w""utf-8")
    as3.write(u"package " + strPackageName + u"\n")
    as3.write(u"{\n")
    as3.write(u"    public class ClassRef\n")
    as3.write(u"    {\n")
    as3.write(u"        public function ClassRef()\n")
    as3.write(u"        {\n")
    for c in RefClassList:
        as3.write(u"            new " + c + u"();\n")
    as3.write(u"        }\n")
    as3.write(u"    }\n")
    as3.write(u"}\n")
    as3.write(u"\n")
    return

def table2key(table, jsonfilename, mapTable, mapParam):
# {"var":"变量名", "filter":"$Online>0 and $Name=='加速锦囊(1小时)'"}
    iRows = table.nrows
    # iCols = table.ncols
    hasMap = (len(mapTable) > 0)
    objDir = os.path.dirname(jsonfilename)
    if objDir and not os.path.exists(objDir):
        os.makedirs(objDir)    
    f = codecs.open(jsonfilename, "w""utf-8")
    strTmp = u""

    # 解析filter字符串
    filterKey = []
    filterString = ""
    if "filter" in mapParam and len(mapParam["filter"]) > 0:
        filterString = mapParam["filter"].decode("utf8")
        filterKey = parseFilterKey(filterString)

    # var xxx = 
    if ("var" in mapParam) and (len(mapParam["var"]) > 0):
        strTmp += u"var " + mapParam["var"] + u" = "

    strTmp += u"{\n"
    f.write(strTmp)
    rs = 0
    for r in range(1, iRows):  # 跳过第1行标题
        strTmp = u"\t"
        i = 0
        strFilter = filterString
        skip_row = False
        get_this = not (len(filterKey) > 0)
        for c in range(2):  # 只处理最前面2列
            title = table.cell_value(0, c)
            isString = (title.rfind(u"\"") >= 0)
            title = title.replace(u"\n", u"").replace(u"\"", u"")

            if hasMap:
                if not title in mapTable:
                    continue
                else:
                    title = mapTable[title]

            strCellValue = u""
            CellObj = table.cell_value(r, c)
            if type(CellObj) == unicode:
                strCellValue = CellObj
            elif type(CellObj) == float:
                strCellValue = FloatToString(CellObj)
            else:
                strCellValue = str(CellObj)

            if isString:
                strCellValue = strCellValue.replace(u"\n", u"").replace(u"\"", u"")

            if not get_this and title in filterKey:
                if isString:
                    strFilter = strFilter.replace(u"$" + title, u"\"" + strCellValue + u"\"")
                else:
                    strFilter = strFilter.replace(u"$" + title, strCellValue)

                if strFilter.find("$") == -1:
                    if not eval(strFilter):  # 被过滤了
                        skip_row = True
                        break
                    else:
                        get_this = True  # 确定了这行要

            if i > 0:
                delm = u":"
            else:
                delm = u""

            if isString:
                strTmp += delm + u"\"" + strCellValue + u"\""
            else:
                strTmp += delm + strCellValue
            i += 1

        if skip_row:  # 被过滤了
            continue
        
        if rs > 0:  # 不是第1行
            f.write(u",\n")
        f.write(strTmp)
        rs += 1

    strTmp = u"\n}\n"
    f.write(strTmp)
    f.close()
    print "Create ", jsonfilename, " OK"
    return

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print 'Usage: %s <excel_file>' % sys.argv[0]
        sys.exit(1)

    print "handle file: %s" % sys.argv[1]

    excelFileName = sys.argv[1]
    data = xlrd.open_workbook(excelFileName)
    table = data.sheet_by_name(u"tablelist")
    rs = table.nrows
    for r in range(rs - 1):
        destTableName = table.cell_value(r + 1, 0)
        destFileName = table.cell_value(r + 1, 2)
        s = "undefined"
        KeyMapParam = {}
        strUseFields = u""
        strKeyFields = u""
        strClassName = u""

        if (table.ncols >= 4):
            strUseFields = table.cell_value(r + 1, 3)

        if (table.ncols >= 5):
            strClassName = table.cell_value(r + 1, 4)

        if (table.ncols >= 6):
            strKeyFields = table.cell_value(r + 1, 5)

        stFieldList = strUseFields.split(",")  # 有用的字段列表

        mapParam = {}

        print "\nCreate " + destTableName + " ==> " + destFileName + " Starting"

        destTable = data.sheet_by_name(destTableName)
        mapTable = readFieldMap(strUseFields)
        KeyMapParam = readFieldMap(strKeyFields)

        suffix = destFileName[destFileName.rfind("."):].lower()
        if suffix == ".csv":
            table2csv(destTable, destFileName, mapTable, mapParam)
        elif suffix == ".jsn" or suffix == ".js":
            table2jsn(destTable, destFileName, mapTable, mapParam)
        elif suffix == ".mall":
            table2mall(destTable, destFileName, mapTable, mapParam)
        elif suffix == ".conf":
            table2ini(destTable, destFileName, mapTable, mapParam)
        elif suffix == ".sql":
            table2sql(destTable, destFileName, mapTable, mapParam)
        elif suffix == ".key":
            table2key(destTable, destFileName, mapTable, mapParam)
        elif suffix == ".cfg":
            table2as3config(destTable, destFileName, stFieldList, strClassName, KeyMapParam)
        else:
            print "only support jsn, ini, csv, conf, sql,.mall, .key, .cfg format"
            exit(1)
        create_ref()
    print "All OK"
posted on 2014-02-08 17:19 冬瓜 阅读(2896) 评论(1)  编辑 收藏 引用 所属分类: 原创python

Feedback

# re: 用python导出excel中的配置 2014-10-21 14:35 createdream
可不可以指导我一下怎么使用这个python脚本,最近也在为写配置而烦恼,我的qq:364642404  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理