python操作excel

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值