import os import xlrd import xlwt from xlutils3.copy import copy from student import Student def open_Excel(excelfile): if os.path.isfile(excelfile): try: excel = xlrd.open_workbook(excelfile) return excel except Exception as e: print(str(e)) def WriteSheetRow(sheet,rowValueList,rowIndex,isBold): i = 0 style = xlwt.easyxf("font:bold 1") for value in rowValueList: if isBold: sheet.write(rowIndex,i,value,style) else: sheet.write(rowIndex,i,value) i = i+1 def open_Excel_ByIndex(excelfile,sheetIndex): excel = open_Excel(excelfile) table = excel.sheets()[sheetIndex] nrows = table.nrows ncols = table.ncols for i in range(nrows): row_data = table.row_values(i) for data in row_data: print(data) def select_student_by_dept(excelfile,deptName): file = open_Excel(excelfile) sheet = file.sheet_by_index(0) info = [] for row in range(sheet.nrows): for col in range(sheet.ncols): if sheet.cell(row,col).value == deptName: info.append(sheet.row_values(row)) return info def del_student_by_id(excelfile,id): file = open_Excel(excelfile) sheet = file.sheet_by_index(0) student_id = sheet.col_values(0)[1:] print(student_id) if id in student_id: id_row = student_id.index(id) for i in range(sheet.row(id_row+1).__len__()): print(sheet.cell(id_row+1,i).value) #Todo else: print("id=%d is not in excel"%id) def get_last_student_id(excelfile): file = open_Excel(excelfile) sheet = file.sheet_by_index(0) student_id = sheet.col_values(0)[1:] return student_id.index(student_id[-1]), student_id[-1] def add_student(excelfile,Student): file = open_Excel(excelfile) new_file = copy(file) sheet = new_file.get_sheet(0) row , student_id = get_last_student_id(excelfile) new_row = row + 2 new_student_id = student_id + 1 Student.id = new_student_id sheet.write(new_row,0,Student.id) sheet.write(new_row,1,Student.name) sheet.write(new_row,2,Student.age) sheet.write(new_row,3,Student.phone) sheet.write(new_row,4,Student.datetime) new_file.save("test2.xls") print(get_last_student_id("test1.xlsx")) student = Student("test06",600,123456789,1996) add_student("test1.xlsx",student)
python操作excel
最新推荐文章于 2023-02-26 13:15:11 发布