python读写Excel文件(xlrd、xlwr)

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

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

excel_file = xlrd.open_workbook(r"D:KeyWordsFrameWork	estScriptssearch.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	estScriptssearch.xlsx")



原文地址:https://www.cnblogs.com/gcgc/p/9503964.html