• python学习笔记7-excel操作


    一、操作excel

    import xlwt
    book = xlwt.Workbook()  #新建一个excel
    sheet = book.add_sheet('sheet1')  #添加一个sheet页
    # sheet.write(0,0,'姓名')
    # sheet.write(0,1,'性别')
    # sheet.write(0,2,'年龄')
    # book.save('case.xls') #微软的office不能用xlsx结尾的,wps随意
    
    
    stus = [
            ['姓名','年龄','性别','分数'],
            ['mary', 20, '', 89.9],
            ['mary', 20, '', 89.9],
            ['mary', 20, '', 89.9],
            ['mary', 20, '', 89.9]
    ]
    book = xlwt.Workbook()  #新建一个excel
    sheet1 = book.add_sheet('sheet1')  #添加一个sheet页
    raw = 0#控制行的
    
    for stu in stus:
        col = 0 #控制列
        for s in stu:
            sheet.write(raw,col,s)
            col+=1
        raw+=1
    
    book.save('kkk.xls')

    二、读取excel

    import xlrd
    book = xlrd.open_workbook('kkk.xls') #打开一个excel
    sheet = book.sheet_by_index(0) #根据顺序获取sheet
    sheet2 = book.sheet_by_name('sheet1') #根据sheet页名字获取sheet
    print(sheet.cell(0,0).value)  #指定行和列获取数据
    print(sheet.ncols) #获取excel里面有多少列
    print(sheet.nrows) #获取excel里面有多少行
    sheet.row_values(1)#取第几行的数据
    print(sheet.col_values(1)) #取第几列的数据
    for i in range(sheet.nrows): # 0 1 2 3 4 5
    	print(sheet.row_values(i)) #取第几行的数据
    

      

    三、修改excel

    from xlutils.copy import copy
    import xlrd
    book1 = xlrd.open_workbook('case.xls')
    book2 = copy(book1)  #拷贝一份原来的excel
    sheet = book2.get_sheet(0) #获取第几个sheet页
    sheet.write(1,3,0)
    sheet.write(1,0,'小黑')
    book2.save('case.xls')
    

      

  • 相关阅读:
    dedecms5.7安装百度(ueditor)编辑器的方法
    shell多线程之进程间通信(2)
    shell多线程之进程间通信
    awk笔记
    用shell做简单的分布式计算
    C语言实现常用查找算法——二分查找
    C语言实现常用排序算法——基数排序
    C语言实现常用数据结构——堆
    C语言实现常用数据结构——图
    C语言实现常用数据结构——二叉查找树
  • 原文地址:https://www.cnblogs.com/SuKiWX/p/8953964.html
Copyright © 2020-2023  润新知