zoukankan      html  css  js  c++  java
  • python学习笔记(十)-- excel操作

    1、execl写操作

    import xlwt
    
    book = xlwt.Workbook()
    sheet = book.add_sheet('哈哈哈')
    sheet.write(0,0,'姓名')#第一个值是行,第一个值是列
    sheet.write(0,1,'成绩')
    sheet.write(1,0,'dsk')
    sheet.write(1,1,90)
    book.save('stu.xls')#存成文件

     2、execl读操作

    import xlrd
    book = xlrd.open_workbook('acount.xls')
    sheet = book.sheet_by_index(0)
    print(sheet.row_values(0))#某一行的数据
    print(sheet.col_values(0))#某一列的数据
    print(sheet.cell(0,0).value)#某个单元格的数据
    print(sheet.cell(1,2).value)
    print(sheet.nrows)#总共多少行
    print(sheet.ncols)#总共多少列
    
    #打印所有行的内容
    for i in range(sheet.nrows):
        print(sheet.row_values(i))

    修改execl内容实例

    import xlrd
    from xlutils import copy
    
    # 1、用xlrd模块打开execl
    # 2、用xltuils模块里面的copy复制一份
    # 3、获取到sheet页
    # 4、修改
    
    book = xlrd.open_workbook('students.xls')
    
    new_book = copy.copy(book)
    sheet = book.sheet_by_index(0)#获取原来数据
    
    sheet2 = new_book.get_sheet(0)#这个是新的sheet项
    sheet2.write(0,6,'年龄阶段')#在第零行第六列添加内容
    
    for i in range(1,sheet.nrows):
        age = sheet.cell(i,3).value #从第一行第三列开始取age的数据
        if age < 18:
            sheet2.write(i, 6, '未成年')
        elif age >= 18 and age <= 30:
            sheet2.write(i, 6, '青年')
        else:
            sheet2.write(i, 6, '中年')
    new_book.save('students.xls')#保存execl表
  • 相关阅读:
    netstat
    ansibe tower的开源替代品semaphore
    ansible playbook 示例
    centos6 安装python2.7
    python celery + redis
    flask + uwsgi 生产环境
    ubuntu访问supermicro ikvm
    [leetcode]Symmetric Tree
    [leetcode]Pascal's Triangle
    [leetcode]Letter Combinations of a Phone Number
  • 原文地址:https://www.cnblogs.com/yanyan-/p/10822647.html
Copyright © 2011-2022 走看看