Python将策划表xlsx转为Lua可用文件

转换规则

定义xlsx文件的前三行分别为:字段描述(即备注字段代表什么),字段名,字段类型
每一行,每一个sheet都分别代表一张table,每一列代表table中的字段
Python将策划表xlsx转为Lua可用文件_第1张图片

转换效果

Python将策划表xlsx转为Lua可用文件_第2张图片

实现方法

定义好模板类型,根据表类型,字段类型得到对应的模板,然后读取Excel的内容填充到模板中,这里记录一下实现的代码,以供需要时拿出来改改用,代码通过变量名应该能读懂,就不写注释了

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Date    : 2020-03-21 18:06:21
# @Author  : yan nan fei
# @Version : $Id$

import os,sys
import xlrd

template="""local DataTable = \n{\n[]\n}
function GetTable() return DataTable end
function GetContent(SheetName) return DataTable[SheetName].Content end
"""

tableTemplate="""%{tablename}={{\n[]\n%}},\n"""


KeyValueTemp="""%{key}={value},\n"""

StringValTemp="""%{key}=[=[{value}]=],\n"""

BoolValTemp="""%{key}={value},\n"""

FuncValTemp="""%{key}=function() return {value} end,"""

vTypeDic={"Int":KeyValueTemp,"String":StringValTemp,"RawData":KeyValueTemp,"Bool":BoolValTemp,"Func":FuncValTemp}


def TemplateParse(template,reg):
	template=template.replace("%",reg)
	return template


def MakeTable(template,tablename,content,depth):
	template=TemplateParse(template,depth*"\t")
	if content!=None:
		template=template.replace("[]",content)
	if isinstance(tablename,float):#如果表key为数字
		tablename="[{key}]".format(key=int(tablename))
	if "tablename" in template:
		template=template.format(tablename=tablename)
	return template

def MakeSubTable(parent,tble2):
	tble=parent.replace("[]",tble2)
	return tble

def MakeKeyValue(vaType,key,value,depth):#根据类型拿到相应模板
	if len(str(key))==0 or len(str(value))==0 or "//" in str(key):
		return ""
	if vaType in vTypeDic:
		template=vTypeDic[vaType]
		template=TemplateParse(template,depth*"\t")
		template=template.format(key=key,value=value)
		return template

class ReadSheetContent:
	def __init__(self,workbook,sheetName):
		self.workbook=workbook
		self.sheetName=sheetName
	def GetContent(self):
		content=""
		sheetContent=self.workbook.sheet_by_name(self.sheetName)
		for row in range(0,sheetContent.nrows):
			if row<3: #前三行分别为备注,变量,变量类型
				continue
			rowTableName=sheetContent.cell_value(row,0)
			rowTableObject=MakeTable(tableTemplate,rowTableName,"[]",3)
			colContent=""
			for col in range(0,sheetContent.ncols):
				key=sheetContent.cell_value(1,col) #第二行表示变量
				vaType=sheetContent.cell_value(2,col)#第三行表示变量类型
				value=sheetContent.cell_value(row,col)
				keyValueObj=MakeKeyValue(vaType,key,value,5)
				colContent=colContent+keyValueObj
			rowTableObject=rowTableObject.replace("[]",colContent)
			content=content+rowTableObject
		return content



if __name__=="__main__":
	if len(sys.argv)>1:
		targetFileName=sys.argv[1]
		targetDir=os.path.dirname(targetFileName)
		if os.path.isdir(targetDir):
			os.makedirs(targetDir)
		workbook=xlrd.open_workbook(targetFileName)
		allSheetNames = workbook.sheet_names();
		fileNameNoExten=targetFileName.split('.')[0]
		with open(fileNameNoExten+".lua","w") as file:
			luaContent=""
			for sheetName in allSheetNames:
				if sheetName=="main":
					continue
				sheetTable=MakeTable(tableTemplate,sheetName,"[]",1)
				ContentTable=MakeTable(tableTemplate,"Content","[]",2)
				sheetTable=MakeSubTable(sheetTable,ContentTable)
				readSheetContent=ReadSheetContent(workbook,sheetName)
				SheetContent=readSheetContent.GetContent()
				luaContent=luaContent+MakeSubTable(sheetTable,SheetContent)
			template=template.replace("[]",luaContent)
			file.write(template)



后续找到更好的方法再扩展,
新加:


import os
import xlrd

#填表规则:前三行分别为备注,变量,变量类型
#变量类型:Int,String,RawData,Bool,Func,Number
#变量类型也可以填:Int|List,这样的类型的值填写如下:
# 2|3|3|4|45|6  =》 最终被解析为{2,3,3,4,45,6}


#解析规则
#{%content%},{%tablename%},{%key%},{%value%}为替换内容
#%~制表符替换

template="""local DataTable = \n{{%content%}\n}
function GetTable() return DataTable end
function GetContent(SheetName) return DataTable[SheetName].Content end
"""

tableTemp="""\n%~{%tablename%}={\n{%content%}\n%~},"""
FuncTemp="""%~{%key%}=function() return {%value%} end,\n"""
KeyValueTemp="""%~{%key%}={%value%},\n"""
StringValTemp="""%~{%key%}=[=[{%value%}]=],\n"""

vTypeDic={"Int":KeyValueTemp,"String":StringValTemp,"RawData":KeyValueTemp,"Bool":KeyValueTemp,"Func":FuncTemp,"Number":KeyValueTemp}

def AddTab(target,reg):
	target=target.replace("%~",reg)
	return target

def MakeTable(target,tablename,content,depth):
	if isinstance(tablename,int) or isinstance(tablename,float):#如果表key为数字
		table=target.replace("{%tablename%}","["+str(int(tablename))+"]")
	else:
		table=target.replace("{%tablename%}",str(tablename))
	if content:
		table=table.replace(r"{%content%}",content)
	table=AddTab(table,depth*"\t")
	return table

def MakeKeyValue(target,key,value,depth):#根据类型拿到相应模板
	if len(str(key))==0 or len(str(value))==0 or "//" in str(key):
		return ""
	if isinstance(key,int) or isinstance(key,float):#如果表key为数字
		table=target.replace("{%key%}","["+str(int(key))+"]")
	else:
		result=target.replace("{%key%}",str(key))
	if value:
		result=result.replace("{%value%}",str(value))
	result=AddTab(result,depth*"\t")
	return result

#----------------------------------------------------------------------------------------------------------
def HandleList(key,value,depth):
	array=str(value).replace("|",",")
	return MakeTable(tableTemp,key,(depth+1)*"\t"+array,depth)

def SearchXlsxFile(baseRoot):
	for root,dirNames,files in os.walk(baseRoot,followlinks=True):
		for f in files:
			filePath=os.path.join(root,f)
			ReadTargetFile(baseRoot,filePath)

def ReadTargetFile(baseDir,filePath):
	fileName=os.path.basename(filePath)
	baseDirname=os.path.basename(baseDir)
	fileDirname=baseDirname+filePath.replace("\\","/").replace(path,"").replace(fileName,"")
	currentDirname=os.path.dirname(os.path.realpath(__file__))
	os.chdir(currentDirname)
	saveDirname=os.path.join(currentDirname,fileDirname)
	if not os.path.exists(saveDirname):
		os.makedirs(saveDirname)
	fileNameNoExten=fileName.split('.')[0]
	saveFile=os.path.join(saveDirname,fileNameNoExten+".lua")
	if fileName.split('.')[1]=="xlsx":
		workbook=xlrd.open_workbook(filePath)
		content=ParseXlsx(workbook)
		content=template.replace(r"{%content%}",content)
		Write2Lua(saveFile,content)

def Write2Lua(saveFile,content):
	with open(saveFile,"w") as file:
		file.write(content)

def ParseXlsx(workbook):
	content=""
	allSheetNames = workbook.sheet_names()
	for sheetName in allSheetNames:
		if sheetName=="main":
			continue
		sheetContent=workbook.sheet_by_name(sheetName)
		rowTable=""
		for row in range(0,sheetContent.nrows):
			if row<3: #前三行分别为备注,变量,变量类型
				continue
			rowTableName=sheetContent.cell_value(row,0)
			if len(str(rowTableName))==0:
				continue
			key_value=""
			for col in range(0,sheetContent.ncols):
				key=sheetContent.cell_value(1,col) #第二行表示变量
				vaType=sheetContent.cell_value(2,col)#第三行表示变量类型
				value=sheetContent.cell_value(row,col)
				if type(vaType)==type(""):
					valueType=vaType.split("|")
					if len(valueType)==1 and valueType[0] in vTypeDic:
						key_value=key_value+MakeKeyValue(vTypeDic[valueType[0]],key,value,4)
					elif len(valueType)==2:
						key_value=key_value+HandleList(key,value,4)
			rowTable=rowTable+MakeTable(tableTemp,rowTableName,key_value,3)
		content=content+MakeTable(tableTemp,sheetName,MakeTable(tableTemp,"Content",rowTable,2),1)
	return content



path="E:/Python/mail"
if __name__ == '__main__':
	SearchXlsxFile(path)

参考文献:
xlrd读表应用举例参照:https://blog.csdn.net/zijikanwa/article/details/89577326
os文件参照:https://www.runoob.com/python/os-file-methods.html

你可能感兴趣的:(Python工具篇)