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

    操作excel安装的三种方式:

      1、pip install xlwt    #写excel

         pip install  xlrd    #读excel

           pip install  xlutils    #修改excel

      2、.whl

           pip install c:/user/niuhanyang/desktop/xxx.whl

      3、.tar.gz

        1、先解压

        2、解压之后在命令行里面进入到这个目录下

        3、执行python   setup.py install

      4、如果安装多个python版本

        python3.5 -m pip instaill XXX

        python2 -m pip instail XXX

        python3.6 -m pip instail XXX

    一、写excel

    import xlwt
    import xlrd
    import xlutils
    
    # 写excel
    book=xlwt.Workbook()
    sheet=book.add_sheet('sheet1')
    # sheet.write(0,0,'id')  #指定行和列内容
    # sheet.write(0,1,'username')
    # sheet.write(0,2,'password')
    #
    # sheet.write(1,0,'1')
    # sheet.write(1,1,'niuhanyang')
    # sheet.write(1,2,'123456')
    
    stus=[
        [1,'njf','1234'],
        [2,'njf1','1234'],
        [3,'njf2','1234'],
        [4,'njf3','1234'],
        [5,'njf4','1234'],
        [6,'njf5','1234'],
        [7,'njf6','1234'],
        [8,'njf7','1234'],
        [9,'njf8','1234'],
        [10,'njf9','1234'],
    ]
    line=0  #控制的是行
    for stu in stus:
        col=0
        for s in stu:
            sheet.write(line,col,s)
            col+=1
        line+=1
    
    book.save('stu.xls')
    

      二、读excel

    import xlrd
    
    book=xlrd.open_workbook('stu.xls')
    sheet=book.sheet_by_index(0)  #根据sheet编号来
    # sheet=book.sheet_by_name('sheet1')   #根据 sheet名称来
    print(sheet.nrows)  #excel里面有多少行
    print(sheet.ncols)  #excel里面有多少列
    print(sheet.cell(0,0).value)  #获取第0行第0列的值
    print(sheet.row_values(0))  #获取到整行的内容
    print(sheet.col_values(0)) #获取到整列的内容
    
    for i in range(sheet.nrows):  #循环获取每行的内容
        print(sheet.row_values(i))
    

      三、修改excel

    import xlrd
    import xlutils
    
    from xlutils import copy    #xlutils中导入copy
    
    book=xlrd.open_workbook('stu.xls')
    #先用xlrd打开一个excel
    new_book=copy.copy(book)
    #然后用xlutils里面的copy功能,复制一个excel
    
    sheet=new_book.get_sheet(0)  #获取sheet页
    
    sheet.write(0,1,'张三')  #修改第0行,第一列
    sheet.write(1,1,'小军')   #修改第一行,第一列
    new_book.save('stu.xls')
    

      

  • 相关阅读:
    浏览器驱动器下载地址
    7.pytest测试完成后通过allure生成测试报告
    6.pytest参数化操作
    5.pytest中fixture的使用(params参数)
    5.pytest中fixture的使用(scope参数)
    4.pytest中固定装置setup和teardown
    3.pytest函数级测试用例和类级测试用例
    2.pytest用例设计及运行
    1.pytest环境搭建
    Pycharm 常用快捷键
  • 原文地址:https://www.cnblogs.com/navysummer/p/11977889.html
Copyright © 2011-2022 走看看