• python(十一)操作excel


    1. 读excel里的内容

    导入模块:import  xlrd

    打开excel,找到sheet,再查找sheet表中的数据,行的值,列的值,具体到某个单元格的数据,可以统计有多少行,多少列数据

    import xlrd
    
    book = xlrd.open_workbook('students.xls')#打开excel表格
    sheet = book.sheet_by_index(0)#找到某个sheet页
    # sheet = book.sheet_by_name('sheet1')
    print(sheet.cell(0,0).value) #指定单元格的内容
    print(sheet.row_values(1))#取整行的数据
    print(sheet.col_values(0))#取整列的数据
    print(sheet.nrows) #多少行
    print(sheet.ncols) #多少列

    2.创建一个新的excel,并往里面写数据

    导入模块:import xlwt

    打开一个excel,在excel中加一个sheet页,要起名字,然后在sheet页中写入参数

    import xlwt
    
    book = xlwt.Workbook()#新建一个book
    sheet = book.add_sheet('sheet1')#新建一个sheet页
    
    
    title = ['编号','姓名','语文成绩','数学成绩','英语成绩','总分','平均分']
    #处理表头
    row = 0
    for t in title:
        sheet.write(0,row,t)#写的方法是:第几行,第几列,要写的内容
        row+=1
    
    data = [
        ["1","小花",99,100,98.5],#1
        ["2","小王",90,30.5,95],#
        ["3","小明",67.5,49.6,88]#
    ]
    
    for row,v in enumerate(data,1): #
        sum_score = sum(v[2:])#算总分
        avg_score = round(sum_score / 3,2) #算平均分
        v.append(sum_score)
        v.append(avg_score)
        for col,value in enumerate(v):
            sheet.write(row,col,value)
    
    book.save("students.xls")  #如果你用的是wps的话 

    3.修改excel里的数据

    导入模块:import  xlutils import xlrd

    首先,通过模块xlrd打开excel,然后通过copy方法,复制excel,然后获取excel中的表,但是方法是get_sheet()然后在指定的单元格内通过写的方法写入新的数据,最后保存新表,新的名字和旧的名字一直

    from xlutils import copy
    import xlrd
    import os
    
    book = xlrd.open_workbook('students.xls')
    
    new_book = copy.copy(book)
    
    sheet = new_book.get_sheet(0)
    sheet.write(0,0,"id")
    sheet.write(0,1,"name")
    
    os.rename('students.xls','students_bak.xls')
    
    new_book.save('students.xls')
  • 相关阅读:
    665. Non-decreasing Array
    35. Search Insert Position
    CompositePattern(组合模式)-----Java/.Net
    BridgePattern(桥接模式)-----Java/.Net
    AdapterPattern(适配器模式)-----Java/.Net
    设计模式系列:原型模式(Prototype Pattern)
    设计模式系列:抽象工厂模式(Abstract Factory Pattern)
    设计模式系列:工厂方法模式(Factory Method Pattern)
    设计模式系列:简单工厂模式(Simple Factory Pattern)
    设计模式系列:单例模式(Singleton Pattern)
  • 原文地址:https://www.cnblogs.com/dmjsd/p/11079452.html
Copyright © 2020-2023  润新知