前言

这个小程序是为了解决pet项目中写配置表的问题。主要功能是把excel表转换为程序可以使用的.cfg格式文件。方便策划直观的填写数据。

代码

# coding:utf-8

import xlrd

import os

import sys



# path = 'F:\\代码仓库\\study\\excel2cfg\\table'

# cfgpath = "F:\\代码仓库\\study\\excel2cfg\\cfg"



# path = 'E:\\代码仓库\\study\\excel2cfg\\table'

# cfgpath = 'E:\\代码仓库\\study\\excel2cfg\\cfg'



exepath = os.path.dirname(os.path.realpath(sys.executable))

path = exepath+'\\table'

cfgpath = exepath+'\\Config'



# 读取help.txt中的数据 xlsx中的数据并且保存为cfg

def readData(files,dirname):

_cfgpath=cfgpath+'\\'+dirname+'.cfg'

exists(_cfgpath)

data=''

for file in files:

if file == 'help.txt':

_lpath=_path+'\\'+file

with open(_lpath,'r',encoding='UTF-8') as f:

data = f.read()

f.close

data += '\n[data]\n'



for file in files:

if file != 'help.txt':

_lpath=_path+'\\'+file



wb=xlrd.open_workbook(_lpath)

sheet=wb.sheet_by_index(0)

rows=sheet.nrows

for i in range(1,rows):

thislist = sheet.row_values(i)

typelist = sheet.row_types(i)

for j in range(0,len(thislist)):

thisvalue = thislist[j]

if typelist[j] == 2:

thisvalue = int(thisvalue)

if j==len(thislist)-1:

data = data + str(thisvalue)

else:

data = data + str(thisvalue) + '\t'

data += '\n'



with open(_cfgpath,'w',encoding="utf-8") as f:

f.write(data)

f.close()



# 判断文件是否存在

def exists(dir):

temp = os.path.exists(dir)

if temp == False:

open(dir,'w')




if __name__=="__main__":

# 读取当前文件夹下的所有文件

dirs=os.listdir(path)

for dir in dirs:

print("正在写入"+dir+'.cfg......')

_path = path+'\\'+dir

files = os.listdir(_path)

readData(files,dir)

print(dir+'.cfg 写入完毕。')