• python读取和写入excel里面的数据(附int变float解决方法)


    好久没写了,今天来说说python读取excel的常见方法。首先需要用到xlrd模块,pip install xlrd   安装模块。

    首先打开excel文件:

    xl = xlrd.open_workbook(r'D:\file\data.xlsx')    传文件路径

    通过索引获取要操作的工作表

    table = xl.sheets()[0]

    有些人不知道啥是工作表,下图这个:

    获取第一行的内容,索引从0开始

    row = table.row_values(0)

    获取第一列的整列的内容

    col = table.col_values(0)

    获取第一列,第0~4行(不含第4行)

    print(table.col_values(0,0,4))

    获取单元格值,第几行第几个,索引从0开始

    data = table.cell(2,0).value

    pycharm读取数据后发现整数变成了小数

    如图,手机号变小数:

    解决办法:在整数内容前加上一个英文的引号即可

    读取excel内容方法截图:

    # todo 对excel的操作
    import xlrd
    
    # todo 打开excle
    xl = xlrd.open_workbook(r'D:\file\data.xlsx')
    #print(xl.read())
    
    # todo 通过索引获取工作表
    table = xl.sheets()[0]
    print(table)
    
    # 获取一共多少行
    rows = table.nrows
    print(rows)
    
    # todo 获取第一行的内容,索引从0开始
    row = table.row_values(0)
    print(row)
    
    # todo 获取第一列的整列的内容
    col = table.col_values(0)
    print(col)
    
    # todo 获取单元格值,第几行第几个,索引从0开始
    data = table.cell(3,0).value
    print(data)

    写入数据到excel的操作:

    '''写入excel文件'''
    import xlsxwriter
    
    # todo 创建excel文件
    xl = xlsxwriter.Workbook(r'D:\testfile\test.xlsx')
    
    # todo 添加sheet
    sheet = xl.add_worksheet('sheet1')
    
    # todo 往单元格cell添加数据,索引写入
    sheet.write_string(0,0,'username')
    
    # todo 位置写入
    sheet.write_string('B1','password')
    
    # todo 设置单元格宽度大小
    sheet.set_column('A:B',30)
    
    # todo 关闭文件
    xl.close()

    方法截图:

    封装读取excel的方法:

    import xlrd
    
    def config_data():
        # 公共参数
        xl = xlrd.open_workbook(r'D:\testfile\config.xlsx')
        table = xl.sheets()[0]
        # todo 获取单元行的内容,索引取值
        row = table.row_values(0)
        return row

    测试是否可用:

    '''测试data里面的配置数据是否可用'''
    from App_automation.data import config_data
    
    
    row = config_data()
    print(row[0])
  • 相关阅读:
    HTML5超科幻个人主页
    用Java开发50个棋类游戏
    Android 4.2 project导入 5.0 SDK Eclipse 开发环境出现的问题总结
    蓝桥杯 地宫寻宝 带缓存的DFS
    HDU2577 How to Type【DP】
    Entity Framework 学习总结之一:ADO.NET 实体框架概述
    ASP.NET MVC4中调用WEB API的四个方法
    ASP.NET MVC Web API 学习笔记---第一个Web API程序
    ASP.Net MVC开发基础学习笔记(1):走向MVC模式
    MVC4笔记 Area区域
  • 原文地址:https://www.cnblogs.com/xiamaojjie/p/11561189.html
Copyright © 2020-2023  润新知