zoukankan      html  css  js  c++  java
  • Python 操作excel

    python操作excel使用xlrd、xlwt和xlutils模块。xlrd模块是读取excel的,xlwt模块是写excel的,xlutils是用来修改excel的

    一、python  读取excel

    import xlrd
    book = xlrd.open_workbook('all_stu.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): # 获取excel中有多少行
    print(sheet.row_values(i)) #取第几行的数据

    二、python 操作excel

    import xlwt
    stus = [
    ['姓名','年龄','性别','分数'],
    ['mary', 20, '', 89.9],
    ['mary', 20, '', 89.9],
    ['mary', 20, '', 89.9],
    ['mary', 20, '', 89.9]
    ]
    book = xlwt.Workbook() #新建一个excel
    sheet = book.add_sheet('sheet1') #添加一个sheet
    sheet.write(0,0,'姓名')#一行一行写入
    # sheet.write(0,1,'性别')
    # sheet.write(0,2,'年龄')
    # book.save('stu.xls') #微软的office不能用xlsx结尾的,wps随意
    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')#微软的office不能用xlsx结尾的,wps随意

    三、python 修改excel

    from xlutils.copy import copy
    import xlrd
    book1 = xlrd.open_workbook('stu.xls')
    book2 = copy(book1) #拷贝一份原来的excel
    sheet = book2.get_sheet(0) #获取第几个sheet
    sheet.write(1,3,0)#写入需要修改的行、列及修改后的值
    sheet.write(1,0,'小黑')
    book2.save('stu.xls')
  • 相关阅读:
    Codeforces Round #647 (Div. 2) E Johnny and Grandmaster
    Codeforces1363E Tree Shuffling
    洛谷P6583 回首过去
    Codeforces 817D Imbalanced Array
    Codeforces 213E Two Permutations
    hdu6312 Game
    树算法笔记(三):Prim最小生成树
    基础数学(四):充分与必要条件
    树算法笔记(二):Kruskal最小生成树
    树算法笔记(一):并查集
  • 原文地址:https://www.cnblogs.com/chendai21/p/8378876.html
Copyright © 2011-2022 走看看