python-封装方法用于读取excel
利用openpyxl方法实现读写excel表格
from openpyxl.reader.excel import load_workbook
import os
class ExcelMethod():
def __init__(self, filename, sheetName):
self.filename = filename
self.wb = load_workbook(filename)
# 通过工作的表名获取一个工作表对象
self.sheet = self.wb[sheetName]
# 获取工作表中的最大行号
self.maxRowNum = self.sheet.max_row
# 获取工作表中的最大列号
self.max_column = self.sheet.max_column
# 获取总的行
self.row = self.sheet.max_row def readExcel(self):
dataList = []
try:
for row in self.sheet.rows:
tmpList = []
for cell in row:
tmpList.append(cell.value)
dataList.append(tmpList)
except:
print("%s加载失败" % self.filename) else:
return dataList[1:] def saveExcel(self, row, text):
try:
self.sheet.cell(row, self.max_column, text)
self.wb.save(self.filename) except:
print("%s 保存失败" % self.filename) if __name__=="__main__":
dri_url = os.path.join(os.getcwd() + r"\User1.xlsx")
excel = ExcelMethod(dri_url,"Sheet1")
dataJson = excel.readExcel()
print(dataJson)
excel.saveExcel(4,'pass')
1.实现获取excel某张表的行数、单元格数据
#coding=utf-8
import xlrd
#获取excel文件
data = xlrd.open_workbook('file_path/xxx.xls')#存放excle表格的路径
#获取第一张表数据
tables = data.sheets()[0]
#打印表行数
print(tables.nrows)
#打印第4行,第3列单元格数据
print(tables.cell_value(3,2))
2.封装获取表格方法
此方法需要实现的作用是:其他方法再调用此方法时,如果传入file_name和sheet_id,就调用对应路径的excel文件和对应的表。如果不传这两个字段,就调用默认表格。
def __init__(self,file_name=None,sheet_id=None):
if file_name:
self.file_name = file_name
self.sheet_id = sheet_id
else:
self.file_name = 'file_path/xxx.xls'
self.sheet_id = 0
self.data = self.get_data()
3.封装获取表格数据方法
封装获取tables的方法,用以之后获取单元格行数、单元格数据,或其他表信息使用。
def get_data(self):
data = xlrd.open_workbook(self.file_name)
tables = data.sheets()[self.sheet_id]
return tables
4.封装获取单元格行数方法
def get_lines(self):
tables = self.data
return tables.nrows
5.封装获取单元格数据的方法
def get_value(self,row,col):
return self.data.cell_value(row,col)
6.封装获取总行数和总列数
def get_nrown_ncols(self):
#获取总行数
rowNum = self.data.nrows
#获取总列数
colNum = self.data.ncols
return rowNum ,colNum
7.写入数据到excel
def write_excel(self,row,column,value_back):
'''
:param row: 某一列
:param value: 需要写入的值
:return:
'''
wb=load_workbook(self.file_name)
sheel = wb[self.sheel_name]
#把值写到row,column组成的单元格
sheel.cell(row,column).value = value_back
#保存excel
wb.save(self.file_name)
8.根据行号查找对应内容
#根据行号,找到该行的内容
def get_row_values(self,row):
tales = self.data
row_data = tales.row_values(row)
return row_data
整体代码如下:
#coding: utf-8
import xlrd class OpeExcel:
def __init__(self,file_name=None,sheet_id=None):
if file_name:
self.file_name = file_name
self.sheet_id = sheet_id
else:
self.file_name = 'file_path/xxx.xls'
self.sheet_id = 0
self.data = self.get_data() #获取sheets的内容
def get_data(self):
data = xlrd.open_workbook(self.file_name)
tables = data.sheets()[self.sheet_id]
return tables #获取单元格行数
def get_lines(self):
tables = self.data
return tables.nrows #获取单元格数据
def get_value(self,row,col):
return self.data.cell_value(row,col) if __name__ == '__main__':
opers = OpeExcel()
print(opers.get_lines())
print(opers.get_value(3,2))
9.给一个excel文件追加内容:
from xlrd import open_workbook
from xlutils.copy import copy
import os
dri_url = os.path.join(os.getcwd()+r"\user.xls")
rexcel = open_workbook(dri_url)# 用wlrd提供的方法读取一个excel文件
rows = rexcel.sheets()[0].nrows # 用wlrd提供的方法获得现在已有的行数
excel = copy(rexcel) # 用xlutils提供的copy方法将xlrd的对象转化为xlwt的对象
table = excel.get_sheet(0) # 用xlwt对象的方法获得要操作的sheet
table.write(1, 3, 'pass') # xlwt对象的写方法,参数分别是行、列、值
excel.save(dri_url) # xlwt对象的保存方法,这时便覆盖掉了原来的excel
python编辑已存在的excel坑: BadZipFile: File is not a zip file
为了能反复编辑已存在的excel文件并保存,需要xlwt、xlrd、xlutils组合起来使用,代码如下:
import xlwt, os, xlrd
from xlutils.copy import copy class Do_Excel:
def __init__(self,filename,sheetname="Sheet1"):
self.filename = filename
self.sheetname = sheetname #读取excel
def excel_read(self,x,y):
data = xlrd.open_workbook(self.filename)
tabel = data.sheet_by_name(self.sheetname)
return tabel.cell_value(x,y) #判断exce文件是否存在,不存在则创建,存在则直接打开编辑
def excel_create(self):
if not os.path.exists(self.filename):
data = xlwt.Workbook()
table = data.add_sheet(self.sheetname)
table.write(0,0,"id")
data.save(self.filename) #综合xlw/xlrd/xlutis.copy 读写excle
def write(self,row,col,value):
self.excel_create()
rb = xlrd.open_workbook(self.filename)
wb = copy(rb)
ws = wb.get_sheet(0)#1代表是写到第几个工作表里,从0开始算是第一个。
ws.write(row,col,value)
wb.save(self.filename) if __name__=="__main__":
dir = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0]
dir_excel = os.path.join(dir+r"\data\user1.xlsx")
Do_Excel(dir_excel).write(2,5,'pass')
解决办法二:直接使用openpyxl的Workbook和load_workbook,简单直接
rom openpyxl import Workbook,load_workbook
import os class Do_Excel:
def __init__(self,filename,sheetname='Sheet1'):
self.filename=filename
self.sheetname=sheetname def write(self,i,j,value):
if not os.path.exists(self.filename):
wb = Workbook()
sh = wb.create_sheet(self.sheetname)
else:
wb = load_workbook(self.filename)
sh = wb[self.sheetname]
sh.cell(i,j).value=value
wb.save(self.filename) Do_Excel('test222.xlsx').write(1,1,'sdcds')
Do_Excel('test222.xlsx').write(1,2,'change')
Do_Excel('test222.xlsx').write(3,2,'pass')
python-封装方法用于读取excel的更多相关文章
- python接口自动化(三十七)-封装与调用--读取excel 数据(详解)
简介 在进行软件接口测试或设计自动化测试框架时,一个不比可避免的过程就是: 参数化,在利用python进行自动化测试开发时,通常会使用excel来做数据管理,利用xlrd.xlwt开源包来读写exce ...
- Python模块安装与读取Excel
今天.想用Python读取一下Excel中的数据,从网上查找了一个样例,是要安装相关的模块: 1:到python官网下载http://pypi.python.org/pypi/xlrd模 ...
- Python学习笔记:读取Excel的xlrd模块
一.安装xlrd 可以使用命令行安装也可使用pycharm进行安装 表示xlrd库已经安装成功,安装成功后,我们就可以导入使用了. 二.xlrd说明 (1.单元格常用的数据类型包括 0:empty(空 ...
- python接口自动化之读取excel表的数据(使用openpyxl模块)
1.安装openpyxl:pip install openpyxl 2.基础知识,直接上代码 import openpyxl #导入模块 wd2=openpyxl.load_workbook('stu ...
- python 【pandas】读取excel、csv数据,提高索引速度
问题描述:数据处理,尤其是遇到大量数据且需要for循环处理时,需要消耗大量时间,如代码1所示.通过data['trip_time'][i]的方式会占用大量的时间 代码1 import time t0= ...
- Python 使用Pandas读取Excel的学习笔记
这里介绍Python中使用Pandas读取Excel的方法 一.软件环境: OS:Win7 64位 Python 3.7 二.文件准备 1.项目结构: 2.在当前实验文件夹下建立一个Source文件夹 ...
- Python读取excel 数据
1.安装xlrd 2.官网 通过官网来查看如何使用python读取Excel,python excel官网: http://www.python-excel.org/ 实例: (1)Excel内容 把 ...
- 基于注解的读取excel的工具包
easyexcel-wraper easyexcel-wraper是什么? 一个方便读取excel内容,且可以使用注解进行内容验证的包装工具 easyexcel-wraper有哪些功能? 在easye ...
- form表单提交,Servlet接收并读取Excel文件
首先是jsp页面: <body scroll=no style="overflow-y:hidden;" onselectstart="return false&q ...
随机推荐
- Multiple plot function
From: http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/ library(ggplot2) multi ...
- jQuery 追加元素、拼接元素的方法总结(append、html、insertBefore、before等)
1. append & appendTo 的功能均为:在被选元素结尾(仍在元素内部)插入指定内容,但是内容和选择器的位置不同 (1) append()方法: $("#test&quo ...
- C语言-第3次作业得分
作业链接:https://edu.cnblogs.com/campus/hljkj/CS201801/homework/2359 作业链接:https://edu.cnblogs.com/campus ...
- Matlab 将RGB 图像转换成YCrCb图像
>> im = imread('trees.jpg');>> imshow(im)>> ycrcb_trees = rgb2ycbcr(im);>> f ...
- node.js同步读取与异步读取文件
- 一个python小爬虫
自定义获取豆瓣网电影TOP250里的排名数量 主要思路:先由requests库获取html基本信息,然后用BeautifulSoup来进行html.parser格式解析,逐个获取Tag属性,并且对内容 ...
- 【[AHOI2005]洗牌 题解
一道好题. 首先是数据范围. 0<N≤10^10 ,0 ≤M≤10^10,且N为偶数 这是这道题的坑点,也是痛点. 10^10表示这这道题必有规律. 那么,first step,我们先探索规律. ...
- 去除 chrome 上保存密码后的 input 框的屎黄色背景
网上找的设置 background-color,background-image 没用,后来找到这个方法测试有效: input:-webkit-autofill { transition: backg ...
- ENSP模拟华为USG6000
- SQL server 多个字段设为主键
create table teacher_course( ton char(8) not null, classno char(8) not null, con char(4) not null pr ...