python+selenium(excel文件操作的读、写方法)

写下excel 文件的一些读写 方法,以后后期要用,这里做下记录

 import xlrd
    import xlwt
    if __name__ == '__main__':
        # #定义Excel文件路径
        excelPath = r'D:\selenium\test.xlsx'#r是转义用的,防止里面有关键字
        #用于读取excel文件
        tableopen = xlrd.open_workbook(excelPath)
        #读取excel工作薄数sheet页
        count = len(tableopen.sheets())
        #print('sheet页数{}'.format(count))
        #获取表数据的行、列数
        table = tableopen.sheet_by_name('1')#获取sheet页,1是sheet页的名字
        h = table.nrows #获取行数
        l = table.ncols#获取列数
        #print('行数为{},列数为{}'.format(h,l))
        #循环读取数据
        for i in range(h):
            rowValues = table.row_values(i)#按行读取数据
            print(rowValues)
            #输出读取数据
            for data in rowValues:
                print(data)
    # 注意这里的 excel 文件的后缀是 xls 如果是 xlsx 打开是会提示无效
        excelpath = r'D:\selenium\test3.xlsx'
        wtbook = xlwt.Workbook()
        #新增一个sheet工作表
        sheet = wtbook.add_sheet('Sheet3',cell_overwrite_ok=True)
        #写入数据头
        headlist = ['学号','姓名','班级']
        row = 0
        col = 0
        #循环写
        for head in headlist:
            sheet.write(row,col,head)
            col = col+1
        for i in range(1,5):#行数限制,我这里写入4行数据
            for j in range(1,3):#列数限制,因为我的headlist有三个数据,所以这里肯定是3列
                #写入4行0~99的随机数
                data = random.randint(0,99)
                sheet.write(i,0,i)
                sheet.write(i,j, data)
            print("写第[%d]行数据"%(i))
    
        #cell_A1 = table.cell(0, 0).value
    
    
        #cell_C4 = table.cell(2, 3).value
        #保存
        wtbook.save(excelpath)

你可能感兴趣的:(py+selenium,py)