用Python操作Excel文件——引言
by AquarHEAD
初六就又开学了,我去把课本什么的取回来,顺便跟马丽娜和伟哥聊了几句,伟哥让我把五次调研考试的成绩单改成每个人的个人成绩分析,昨晚和今天上午就去研究怎么用Python操作Excel了(其实上次和海龙研究了怎么用Java操作,不过看完Python的代码之后就发誓坚决不用Java了。。。)
直接Google返回这个网站,很好很强大,也可以直接下载我把3个Package和那个Tutorial打包在一起的文件。
各种解压之后安装,再来几个import就可以很爽地用Python操作.xls文件了。
我还没拿到具体的成绩单,不过我暂时做了个测试用的小程序,把代码贴过来围观一下Python的强大。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | # coding=utf-8 from xlrd import * from xlwt import * from tempfile import * import glob names = [] outfiles = [] now_row = 1 def find_ouf(now_name): if names.count(now_name) == 0: names.append(now_name) temp_ouf = Workbook() outfiles.append(temp_ouf) outfiles[len(outfiles)-1].add_sheet('Analysis') temp_ous = outfiles[len(outfiles)-1].get_sheet(0) temp_ous.write(0,0,now_name) temp_ous.write(1,1,u'数学') temp_ous.write(1,2,u'语文') temp_ous.write(1,3,u'英语') temp_ous.write(1,4,u'物理/理综') temp_ous.write(1,5,u'化学') temp_ous.write(1,6,u'生物') return outfiles[names.index(now_name)] infiles = glob.glob('*.xls') for num_inf in range(len(infiles)): now_inf = open_workbook(infiles[num_inf]) now_ins = now_inf.sheet_by_index(0) now_row += 1 for row in range(2,now_ins.nrows): now_name = unicode(now_ins.cell(row,1).value) now_ouf = find_ouf(now_name) now_ous = now_ouf.get_sheet(0) now_ous.write(now_row,0,now_ins.cell(0,0).value) for each in range(len(outfiles)): outfiles[each].save(names[each]+'.xls') outfiles[each].save(TemporaryFile()) |