昨晚有需求写一个处理excel的小脚本,不属于游戏范畴,想了下没用lua实现,拾起老朋友python撸了一通。
首先介绍下python超实用的工具pip:这工具可以很方便的线上安装依赖库。这次操作excel使用了xlrd和xlwt两个扩展包,用pip安装之,考虑到需求方没有python环境,需要将脚本制作成可运行exe,需要再安装pyinstaller。
下面直接上代码:
#-*- coding:utf-8 -*-
import xlrd
import xlwt
#这里是每次要修改的配置
sTargetExcel = '2017年1-12集团工资表.xlsx'#文件名
nMaxRow = 100#最大行数
nTargetVal = 21#要采集数据所在的列(excel的第1列对应的是0)
dTotalInfo = {}#{名字:{bumen:"部门名",dIncome:{1:xx,2:xx,}}}
workbook = xlrd.open_workbook(sTargetExcel)
sheet_names= workbook.sheet_names()
nSheetIndex = 0
for sheet_name in sheet_names:
nSheetIndex += 1
if nSheetIndex == 1:
continue
sheet = workbook.sheet_by_name(sheet_name)
print sheet_name
for nRow in range(2,nMaxRow):#excel从0开始
try:
listRows = sheet.row_values(nRow)#获取第nRow行内容
except:
continue
sBumen, sName, nIncom = listRows[0], listRows[2], listRows[nTargetVal]
#print nRow, sBumen, sName, nIncom
try:
int(sName)
continue
except:
pass
if len(sName) == 0:
continue
if not sName in dTotalInfo.keys():
dTotalInfo[sName] = {"bumen":sBumen, "dIncome": {}}
dIncomeInfo = dTotalInfo[sName]["dIncome"]
nMonth = int(sheet_name)%100
dIncomeInfo[nMonth] = nIncom
print(dTotalInfo)
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('dTotalInfo')
sheet.write(0, 0, "name")
sheet.write(0, 1, "bumen")
for nMonth in range(1, 13):
sheet.write(0, 1 + nMonth, "%d Month"%nMonth)
nRow = 1
for sName, dPersonInfo in dTotalInfo.items():
sheet.write(nRow, 0, sName)#第nRow行第1列写入内容
sheet.write(nRow, 1, dPersonInfo["bumen"])
dIncomeInfo = dPersonInfo["dIncome"]
for nMonth in range(1, 13):
nIncom = dIncomeInfo.get(nMonth)
if not nIncom:
continue
sheet.write(nRow, 1 + nMonth, nIncom)
nRow += 1
wbk.save('test.xlsx')
有一部分是需求功能。调试好之后,能正常生成一个新的test.xlsx文件。
最后调出cmd命令框,输入pyinstaller -F /脚本名,即可将脚本打包成可执行exe文件。需要注意pyinstaller是否在环境PATH里配好。
本文介绍了一个使用Python处理Excel文件的实战案例,通过xlrd和xlwt库读取和写入Excel数据,实现了数据采集和汇总的功能,并最终生成新的Excel文件。

被折叠的 条评论
为什么被折叠?



