好久没写了,今天来说说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 打开exclexl = xlrd.open_workbook(r'D:\file\data.xlsx')#print(xl.read())# todo 通过索引获取工作表table = xl.sheets()[0]print(table)# 获取一共多少行rows = table.nrowsprint(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).valueprint(data)
写入数据到excel的操作:
'''写入excel文件'''import xlsxwriter# todo 创建excel文件xl = xlsxwriter.Workbook(r'D:\testfile\test.xlsx')# todo 添加sheetsheet = 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 xlrddef 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_datarow = config_data()print(row[0])
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。