300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python中xlrd和xlwt模块读写excel使用方法

python中xlrd和xlwt模块读写excel使用方法

时间:2022-12-25 20:20:01

相关推荐

python中xlrd和xlwt模块读写excel使用方法

一、xlrd模块和xlwt模块是什么

xlrd模块是python第三方工具包,用于读取excel中的数据;

xlwt模块是python第三方工具包,用于往excel中写入数据;(只能创建新表格,不能修改表格内容!)

二、xlrd模块和xlwt模块的安装

pip install xlrd

pip install xlwt

三、Excel表格结构如下:

四、使用xlrd模块读取excel文件

#读取excel数据

def read_excel(self,excel_path,sheet_name):

xls = xlrd.open_workbook(excel_path,formatting_info=True) # 先打开已存在的表,formatting_info=True表示保留原表格的样式

sheet = xls.sheet_by_name(sheet_name) # 通过sheet名称获得sheet对象

dataList = []

for rows in range(1,sheet.nrows):#循环行

tempList = []

for cols in range(0,sheet.ncols-2):#循环列,因为最后两列是写入结果的所以减2

if cols==0:#判断如果是第一列则直接设置行数。

tempList.append(rows)

else:

tempList.append(sheet.cell_value(rows,cols))

dataList.append(tempList)

return dataList

read_excel方法参数说明:

excel_path参数为excel文件的路径,

sheet_name参数excel文件中的sheet名称。

五、独行踽近,众行致远!

如果你觉得此文对你有帮助,如果你对此文有任何疑问,如果你对软件测试、接口测试、自动化测试、面试经验交流感兴趣都可以加入软件测试技术群:695458161,群里发放的免费资料都是笔者十多年测试生涯的精华。还有同行一起交流哦。

六、使用xlrt模块向excel文件中写入数据

#向excel中写入数据

def write_excel(self,excel_path,sheet_name,rows,cols,value):

#获得当前系统时间

current_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())

# 打开已存在的表,formatting_info=True表示保留原表格的样式

book = xlrd.open_workbook(excel_path,formatting_info=True)

wb = copy(book) # 复制excel

sheet = wb.get_sheet(sheet_name) #通过sheet名称获得sheet对象

if value == 'fail':

sheet.write(rows,cols,value,style=xlwt.easyxf('pattern: pattern solid,fore_colour red;')) # 引用样式

elif value == 'ignore':

sheet.write(rows,cols,value,style=xlwt.easyxf('pattern: pattern solid,fore_colour yellow;')) # 引用样式

else:

sheet.write(rows,cols,value)

#设置时间列的宽度和值

sheet.col(cols-1).width = 5000

sheet.write(rows,cols-1,current_time)

#保存

wb.save(excel_path)

read_excel方法参数说明:

excel_path参数为excel文件的路径,

sheet_name参数excel文件中的sheet名称。

rows参数把内容写入到第几行

cols参数表示把内容写入到第几列

value参数表示写入的内容

七、执行代码如下:

if __name__ == '__main__':

eu = ExcelUtil()

#print(eu.read_excel(get_project_path()+"data/testdata.xls","查询火车票"))

eu.write_excel(get_project_path()+"data/testdata.xls","查询火车票",1,6,"pass")

eu.write_excel(get_project_path()+"data/testdata.xls","查询火车票",2,6,"ignore")

eu.write_excel(get_project_path()+"data/testdata.xls","查询火车票",3,6,"fail")

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。