将每个学生填写的信息在检查后自动汇总到一个新的excel表格。
#-*- encoding: utf-8 -*- ‘‘‘ 小学 学生学籍信息汇总 (带身份证号码有效性检查) 版权:GPL owner:[email protected] ‘‘‘ import os #import xlrd import xlwt from xlrd import open_workbook from xlutils.copy import copy import re import traceback def check_id( idcard ): ‘‘‘ 检查身份证号的有效性 ‘‘‘ s = idcard[:-1] #"34052419800101001" #分组 temp = zip(s[0:17], [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]) #相乘 temp2 = map(lambda x:int(x[0])*x[1], temp) #print temp2 #相加 temp3 = sum(temp2) #或者这样写: #temp3 = reduce(lambda x, y : x + y, temp2)print temp3 #最终结果 tmp = ‘10X98765432‘ res = tmp[temp3 % 11] if idcard[ -1] != res: raise Exception("身份证号码错误") def read_one_file (targetFile,sheetName): #打开excel文件,formatting_info=True可以指定保存格式 data = open_workbook(filename=targetFile,formatting_info=True) #table = data.sheets()[0] #通过索引顺序获取 #table = data.sheet_by_index(0) #通过索引顺序获取 table = data.sheet_by_name( sheetName )#通过名称获取 ##读取有意义的内容 row_value = table.row_values(1) ## TODO 应该检查 ## 出生地、户籍所在地, 只保留代码。。 def addr_code( row_value, index): ## 如果为空则不检查 if row_value[index]: row_value[index] = re.search("\d+",row_value[index]).group() try: addr_code(row_value, 4) addr_code(row_value, 14) addr_code(row_value, 51) addr_code(row_value, 63) ## 身份证号检查, 第12项 check_id( row_value[12] ) #班级检查 assert row_value[15] == "2015102" #入学年份检查 assert row_value[16] == "201509" #入学方式: assert row_value[17] == "就近入学" assert row_value[18] == "走读" print (row_value) except Exception as e: print (traceback.format_exc() ) print ("Error", filename) print (e) #for index , value in enumerate(row_value): #if "130104200905133362" in value: #print (index) #if ("000000" in value): #print (index, value) return row_value def read_files( dir_path ): for filename in os.listdir(path=dir_path): if filename.endswith("xls"): file_path = os.path.join(dir_path, filename) yield read_one_file(file_path, sheetName="学生基础信息") def write2file(targetFile,dir_path): #w = xlwt.Workbook() #ws = w.add_sheet(‘学生基础信息‘) ##dir_path = r‘H:\Work\Python\xueji\app\input_files‘ #for row_index, row in enumerate( read_files(dir_path) ): #for col_index , col_value in enumerate(row): #ws.write(row_index, col_index, col_value ) #注意单元格坐标从(0,0)开始 #w.save(targetFile) #import csv #with open( targetFile, mode="w") as f: #writer = csv.writer( f ) #for row_index, row in enumerate( read_files(dir_path) ): #writer.writerow(row) from openpyxl import Workbook wb = Workbook() # grab the active worksheet ws = wb.active for row_index, row in enumerate( read_files(dir_path) ): #writer.writerow(row) # Rows can also be appended ws.append( row ) wb.save("./output/output.xlsx") if __name__ =="__main__": dir_path = r‘H:\Work\Python\xueji\app\input_files‘ write2file( "./output/学籍模板最新正式统计表.csv", dir_path) #read_files(dir_path)
时间: 2024-10-13 11:52:14