|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 苏丛 于 2018-3-8 18:04 编辑
准备工作:安装xlrd, xlwt模块, 一些个人无课表
操作方法:将个人无课表与小程序放在同一个文件夹里,运行程序
注意事项:个人无课表的格式要符合模板的, 文件名为:名字.xlsx (eg 苏丛.xlsx)
模板如图
代码如下
- import os
- import xlrd
- import xlwt
- #打开当前目录
- all_files = os.listdir(os.curdir)
- #用来收集.xlsx文件的列表
- file = []
- target = '无课'
- loc_dict = {}
- #获得无课的坐标和课表所有人
- def get_loc():
- #收集.xlsx文件
- for each_file in all_files:
- if os.path.splitext(each_file)[1] == '.xlsx':
- file.append(each_file)
- #收集坐标和名字数据
- for each_file in file:
- name = os.path.splitext(each_file)[0]
- workbook = each_file
- #打开文件
- with xlrd.open_workbook(workbook) as wb:
- #打开第一个表格
- sheet = wb.sheets()[0]
- #遍历表格,查找目标
- for row_num in range(sheet.nrows):
- for col_num in range(sheet.ncols):
- #记录坐标和名字数据
- if sheet.cell_value(row_num, col_num) == target:
- try:
- loc_dict[row_num, col_num] += ' ' + name
- except KeyError:
- loc_dict[row_num, col_num] = name
- def get_frame(sheet):
- #获得课表框架
- with xlrd.open_workbook(file[0]) as frame:
- sheet = frame.sheets()[0]
- frame_col = sheet.col_values(0)
- frame_row = sheet.row_values(0)
- return frame_col, frame_row
- def write_name(sheet):
- #写入姓名
- for each_loc in loc_dict:
- #四个参数分别是纵坐标,横坐标,名字
- sheet.write(each_loc[0], each_loc[1], loc_dict[each_loc])
- #写入框架
- def write_frame(frame_col, frame_row, sheet):
- loc = 0
- for each_row in frame_row:
- sheet.row(0).write(loc, each_row)
- loc += 1
-
- loc = 0
- #这里不知道为什么不能跟上面写入一行一样地写入一列。
- for each_col in frame_col:
- sheet.write(loc, 0, each_col)
- loc += 1
- def write_workbook():
- #创建一个新的课表
- new_wb = xlwt.Workbook()
- sheet = new_wb.add_sheet('无课表', cell_overwrite_ok = True)
- frame_col, frame_row = get_frame(sheet)
- write_frame(frame_col, frame_row, sheet)
- write_name(sheet)
- new_wb.save('无课表.xls')
- if __name__ == '__main__':
- get_loc()
- write_workbook()
-
复制代码
还有一些问题:
不能保存为.xlsx文件
我在想加一个检测功能:检测出不符合模板的文件,然后生成一个txt文件。但还没想好怎么写。
还请在座的各位大佬不吝赐教!
有任何做的不好的都提出来,小毛病大毛病都行,或者有哪些不好的编程习惯都可以指出来
嘻嘻嘻
|
|