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设计】。

相关文章

Python读取xlsx文件的实现方法

脚本如下: from openpyxl import load_workbook workbook = load_workbook(u'/tmp/test.xlsx') #找到需...

浅谈Python 的枚举 Enum

枚举是常用的功能,看看Python的枚举. from enum import Enum Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'A...

Python内置数据结构与操作符的练习题集锦

第一题: give you two var a and b, print the value of a+b, just do it! 根据提议,给出两个变量 a 和 b 并打印出 a+b...

Python使用Opencv实现图像特征检测与匹配的方法

Python使用Opencv实现图像特征检测与匹配的方法

特征检测是计算机对一张图像中最为明显的特征进行识别检测并将其勾画出来。大多数特征检测都会涉及图像的角点、边和斑点的识别、或者是物体的对称轴。 角点检测 是由Opencv的cornerH...

详解Python中的format格式化函数的使用方法

详解Python中的format格式化函数的使用方法

format函数实现字符串格式化的功能 基本语法为: 通过 : 和 {} 来控制字符串的操作 一、对字符串进行操作 1. 不设置指定位置,按默认顺序插入 ①当参数个数等于{}个数的时候...