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 转义字符详细介绍

Python 转义字符 在需要在字符中使用特殊字符时,python用反斜杠(\)转义字符。如下表: 原始字符串 有时我们并不想让转义字符生效,我们只想显示字符串原来的意思,这就要用r和...

python中获得当前目录和上级目录的实现方法

获取当前文件的路径: from os import path d = path.dirname(__file__) #返回当前文件所在的目录 # __file__ 为当前文件...

python 实现单通道转3通道

下面有两种方法都可以: import numpy as np a=np.asarray([[10,20],[101,201]]) # a=a[:,:,np.newaxis] # p...

解决python3中自定义wsgi函数,make_server函数报错的问题

#coding:utf-8 from wsgiref.simple_server import make_server def RunServer(environ, start_...

总结用Pdb库调试Python的方式及常用的命令

用Pdb调试有多种方式 使用 Pdb调试 Python的程序的方式主要是下面的三种!下面逐一介绍 命令行加-m参数 命令行启动目标程序,加上-m参数,这样调用 testPdb.py的...