一个xlsx转lua的python小工具

目录结构:
目录结构:
xlsx文件格式:
一个xlsx转lua的python小工具_第1张图片
xlsxToLua.py如下:

import xlrd
import os

def toLua():
    pwd = "./"
    fileList = list(os.listdir(pwd))  # 列出文件夹下所有的目录与文件
    for file in fileList:
        if file.find(".xlsx") > 0 and ( file.find("~") < 0 ):
            fileName = file[:file.find(".xlsx")]
            print("开始转化:", fileName)
            filepwd = pwd + "/" + file
            with xlrd.open_workbook(filepwd) as workbook:
                sheet1 = workbook.sheet_by_index(0) # sheet索引从0开始
                nrows = sheet1.nrows
                keyList = []
                strFlie = "-- $Id$\nmodule(\"Data\")\n\n"
                strFlie = strFlie + fileName + " = { \n"
                IDindex = 0
                for i in range(nrows):
                    valueList = sheet1.row_values(i)
                    if valueList[0] == "ID":
                        keyList = valueList
                        IDindex = i
                    if i > IDindex and IDindex > 0:
                        str1 = "    [" + str(i - IDindex) + "] = {"
                        for j in range(len(valueList)):
                            value = valueList[j]
                            if value == "":
                                value = (sheet1.row_values(i - 1)[j])
                            if type(value) == type(1.0) or type(value) == type(1):
                                str1 = str1 + keyList[j] + " = " + str(int(value)) + ", "
                            else:
                                str1 = str1 + keyList[j] + " = \"" + str(value) + "\", "
                        str1 = str1[:len(str1) - 2] + "}\n"
                        strFlie = strFlie + str1

                strFlie = strFlie + "}"
                print(strFlie)

                #写入文件
                with open("./toLua/" + fileName + ".lua", "w+", encoding='utf-8') as f:
                    f.write(strFlie)
                    f.close()


if __name__ == "__main__":
    toLua()


运行结果:
一个xlsx转lua的python小工具_第2张图片
生成文件:一个xlsx转lua的python小工具_第3张图片

你可能感兴趣的:(python,lua,xlsx)