python读写Excel文件(xlrd、xlwr)

一、首先需要安装第三方库:pip install xlrd

1、打开Excel文件,由于写入时需要copy,所以这里加上保留原格式参数:formatting_info=True

excel_file = xlrd.open_workbook(r"D:\KeyWordsFrameWork\testScripts\search.xlsx", formatting_info=True)

2、获取打开文件的sheet页

sheet = excel_file.sheet_by_index(0) # 以索引方式获取,从0开始

sheet = excel_file.sheet_by_name('sheet1') # 以sheet页名称方式获取

 

3、获取最大行数和列数

rows_num = sheet.nrows # 获取行数

cols_num = sheet.ncols # 获取列数

4、获取某个单元格的值

# 获取第一行第四列的单元格内容
cell = sheet.row_values(0)[3] 
#一般情况会遍历取值,如下:

for row in range(1, sheet.nrows):  # 循环用例步骤
  keyword = sheet.row_values(row)[2]  # 读取关键字列

5、写入:向已经存在的excel写入

  需要用到这个库

  from xlutils.copy import copy

#需要先将原来的excel_file拷贝一下
excle_fileCopy = copy(excel_file)
# copy后的excel_fileCopy需要使用get_sheet()方法获取sheet页,而不是上面的sheet_by_index(0)
case_sheet = excle_fileCopy.get_sheet(0)
# 写入case_sheet,第三个参数为需要写入的值
case_sheet.write(row0, 5, take_time)
case_sheet.write(row0, 6, retDict['result'])
# 最后需要保存一下                         
excle_fileCopy.save(r"D:\KeyWordsFrameWork\testScripts\search.xlsx")

 

 

 
 


转载于:https://www.cnblogs.com/gcgc/p/9503964.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值