zoukankan      html  css  js  c++  java
  • python基础七--操作excel

    操作excel(读、写、修改),模块:xlrd、xlwt 和 xlutils。

    1、读excel

    import xlrd   #读excel
    
    book = xlrd.open_workbook(r'students.xlsx')   #打开excel
    print(book.sheet_names())   #获取所有sheet的名字
    sheet = book.sheet_by_index(0)   #根据sheet页的位置去取sheet
    # sheet2 = book.sheet_by_name('Sheet2')   #根据sheet页的名字获取sheet页
    print(sheet.nrows)   #获取sheet页里面的所有行数
    print(sheet.ncols)   #获取sheet页里面的所有列数
    print(sheet.row_values(0))   #根据行号获取整行的数据
    print(sheet.col_values(0))   #根据列获取整列的数据
    print(sheet.cell(1,1).value)   #cell方法是获取指定单元格的数据,前面是行,后面是列
    
    lis = []
    for i in range(1,sheet.nrows):   #i代表的是每一行,因为第一行是表头,所以直接从第二行开始循环
        d = {}
        id = sheet.cell(i,0).value   #行是不固定的,列是固定的
        name = sheet.cell(i,1).value
        sex = sheet.cell(i,2).value
        d['id']=int(id)
        d['name']=name
        d['sex']=sex
        lis.append(d)
    print(lis)

    2、写excel

    import xlwt   # 写excel
    
    lis = [{'id': 1, 'name': '小明', 'sex': ''},
           {'id': 2, 'name': '小黑', 'sex': ''}]
    title = ['编号','姓名','性别']
    
    book = xlwt.Workbook()   #新建一个excel对象
    sheet = book.add_sheet('stu')   #添加一个sheet页
    sheet.write(0,0,'编号')
    book.save('stu.xls')
    
    book = xlwt.Workbook()   #新建一个excel对象
    sheet=book.add_sheet('new_stu')
    for i in range(len(title)):
        sheet.write(0,i,title[i])
    for row in range(len(lis)):
        id = lis[row]['id']   #因为lis里面存的是一个字典,lis[row]就代表字典里面的每个元素,然后字典取值   #固定的key就可以了
        name = lis[row]['name']
        sex = lis[row]['sex']
        new_row = row+1  #因为循环的时候是从0开始循环的,第0行是表头,不能写  #要从第二行开始写,所以这里行数要加一
        sheet.write(new_row,0,id)
        sheet.write(new_row,1,name)
        sheet.write(new_row,2,sex)
    book.save('new_stu.xls')

    3、修改excel

    import xlrd
    from xlutils.copy import copy
    
    book = xlrd.open_workbook('new_stu.xls')  #打开原来的excel
    new_book = copy(book)   #通过xlutils里面copy复制一个excel对象
    sheet = new_book.get_sheet(0)   #获取sheet页
    sheet.write(0,0,'id')
    new_book.save('new_stu.xls')   #保存文件名称不变会覆盖原有文件
  • 相关阅读:
    o9.17,习题
    09.17,二维数组,地图
    09.15,一维数组,冒泡排序
    09.11 小兔 成兔问题
    09.01,学习习题
    FTPHelper
    Wpf发送接收 win32消息
    win32Helper
    xml 封装类
    C# 多进程安全
  • 原文地址:https://www.cnblogs.com/eeoo/p/7132372.html
Copyright © 2011-2022 走看看