使用python导出Excel表格中的lua配置

背景:游戏开发中, 策划使用Excel配置游戏中的参数数据,写一个工具用于导出这些配置

工具选择使用 python来开发,这样Windows、macOS、Linux平台都可以使用,而且有丰富的第三方模块。

本机先安装python,我这边使用的是python3.10.6。

确定Excel的结构

假设我们需要的配置是这种结构的:

lua 复制代码
Items = {
	[1001] = { id = 1001, name = "新手武器", level = 1, attrs = { atk = 10 }, icon = "resource/items/1001.png" },
	[1002] = { id = 1002, name = "新手衣服", level = 1, attrs = { def = 10 }, icon = "resource/items/1002.png" },
	[1003] = { id = 1003, name = "新手护手", level = 1, attrs = { atk = 3, def = 3 }, icon = "resource/items/1003.png" }
}

表格中则为这样:

我们称每一个Items项为ItemData,第一行为ItemData的中所有的key,第一列为ItemData在Items表中的key,从第二行开始每一格填入所在列的key对应的值,然后我们直接以文本格式读取所有内容,用=号连接key和value即可。

文件命名为:道具表.xlsx,表单名先设置为lua配置的表名:Items。

生成配置文件config.lua的代码大概是这种模式:

python 复制代码
with open('config.lua', 'w', encoding="utf-8") as file:
    file.write("Items = {\n")

	#写入表格数据

    file.write("}")

生成文件:

读取Excel中的数据

Excel中的数据这里使用pandas模块来读取,然后写入config.lua中

先安装padas:pip install pandas

python 复制代码
import pandas

#参数1是Excel文件路径
#参数2是表单名 
#参数header=n表示表头在第n+1行,没有表头则不填,我们这里表头在第一行所以填0
#参数dtype="str"表示格子内的数据按字符串格式读取
#返回值是pandas读取表单生成的DataFrame
df = pandas.read_excel(".//配置表.xlsx", "Items", header=0, dtype="string")

#数据的行、列数
row, column = df.shape

with open('config.lua', 'w', encoding="utf-8") as file:
    file.write("Items = {\n")

    #遍历所有行 每一行是一条 ItemData
    for r in range(row):
        row_data = df.iloc[r,:]

        #第一列是ItemData 的 key
        #df.columns 是表头内容
        key = row_data[df.columns[0]]
        file.write(f"[{key}]=")
        file.write("{")
    
        #遍历所有列 
        for c in range(column):
            sub_key = df.columns[c]
            sub_value = row_data[sub_key]
            file.write(f"{sub_key} = {sub_value}, ")

        file.write("},\n")


    file.write("}")

导出所有表单

pandas可以通过下述方法遍历sheet列表:

python 复制代码
import pandas

ef = pandas.ExcelFile(".//配置表.xlsx")
for name in ef.sheet_names:
	# read_excel的参数1也可以使用ExcelFile
	df = pandas.read_excel(ef, name, header=0, dtype="string")
	
	#数据的行、列数
	row, column = df.shape
	
	with open('config.lua', 'w', encoding="utf-8") as file:
		file.write(name)
	    file.write(" = {\n")
		
		... 
		...
相关推荐
MasonYyp13 分钟前
声音转文字的模型
python
信誓旦旦的程序猿8 小时前
【Python量化实战宝典 #08】可转债与债券接口手册:转股价·溢价率·纯债价值(Python 可跑)
java·python·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
砚底藏山河8 小时前
python量化:行情数据回溯
java·开发语言·python·金融·maven
今年下半年8 小时前
AI智能体项目实战记录(02):初始化 Python 项目
开发语言·人工智能·python·fastapi
reasonsummer8 小时前
【办公类-53-12】20261016(预测)Python模仿制作2026学年第二学期校历(excel+pdf,上下学期都包含)
pdf·excel
Williamtym8 小时前
PickGo Lab实践:用浏览器、Python和MCP串起机器人搬运仿真
开发语言·python·机器人
CS创新实验室8 小时前
Python 对象“死“了之后去了哪?——引用计数与分代垃圾回收
开发语言·jvm·python
CCblandy8 小时前
雪花 ID 四个边界实测:时钟回拨重号 500 个,前端 JSON.parse 直接丢精度
后端·python·算法·性能优化·架构
quantdash_cc9 小时前
Pandas 处理分钟级股票行情:从原始数据清洗到 K 线聚合
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
把我格子衫拿来9 小时前
VTK 9.5 与 Qt 6 联合开发:从嵌入三维窗口到可维护的桌面架构
c++·python·qt·vtk·三维可视化