PYTHON如何读取和写入EXCEL里面的数据

yipeiwu_com6年前Python基础

好久没写了,今天来说说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])

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用TensorFlow实现简单线性回归模型

使用TensorFlow实现简单线性回归模型

本文使用TensorFlow实现最简单的线性回归模型,供大家参考,具体内容如下 线性拟合y=2.7x+0.6,代码如下: import tensorflow as tf import...

python之cv2与图像的载入、显示和保存实例

python之cv2与图像的载入、显示和保存实例

本文是OpenCV 2 Computer Vision Application Programming Cookbook读书笔记的第一篇。在笔记中将以Python语言改写每章的代码。 P...

python中for用来遍历range函数的方法

python中for用来遍历range函数的方法

栗子:计算斐波那契数列(任一个数都是前两个数之和的数字序列) Python2.7实现代码如下: <strong><span style="font-size:14p...

浅析python中numpy包中的argsort函数的使用

浅析python中numpy包中的argsort函数的使用

概述 argsort()函数在模块numpy.core.fromnumeric中。 在python中排序数组,或者获取排序顺序的时候,我们常常使用numpy包的argsort函数来完成。...

Python使用grequests(gevent+requests)并发发送请求过程解析

前言 requests是Python发送接口请求非常好用的一个三方库,由K神编写,简单,方便上手快。但是requests发送请求是串行的,即阻塞的。发送完一条请求才能发送另一条请求。...