“ 对于 excel 格式的文件,建议使用 xlrd、xlwt 模块。”
目录
一、Python XLRD
二、Python XLWT
一、Python XLRD
读取 excel 表格数据,支持 xlsx 和 xls 格式的 excel 表格。
import xlrd
# 打开excel文件
workbook = xlrd.open_workbook(filename)
# 获取workbook对象中的所有sheet对象
sheets = workbook.sheets()
# 获取workbook对象中的所有sheet名称
sheet_names = workbook.sheet_names()
# 通过索引获取sheet对象
sheet = workbook.sheet_by_index(index)
# 通过名称获取sheet对象
sheet = workbook.sheet_by_name(name)
# 行操作 ##############################
# 获取sheet对象中的有效行数
nrows = sheet.nrows
# 获取sheet对象中第rowx+1行的长度
row_len = sheet.row_len(rowx)
# 获取sheet对象中第rowx+1行, [start_colx, end_colx]区间列的单元值, 返回列表
values = sheet.row_values(rowx, start_colx=0, end_colx=None)
# 获取sheet对象中第rowx+1行的cell, 返回列表
cells = sheet.row(rowx)
# 以切片方式获取sheet对象中第rowx+1行, [start_colx, end_colx]区间列的数据, 返回列表
cells_slice = sheet.row_slice(rowx, start_colx=0, end_colx=None)
# 获取sheet对象中第rowx+1行, [start_colx, end_colx]区间列的单元类型, 返回array.array类型
cells_array = sheet.row_types(rowx, start_colx=0, end_colx=None)
# array中的元素为单元的类型, 对应如下:
# 0-空 1-string 2-number 3-date, 4-boolean 5-error
# 列操作 ##############################
# 获取sheet对象中的有效列数
ncols = sheet.ncols
# 获取sheet对象中第colx+1列, [start_rowx, end_rowx]区间行的单元值, 返回列表
values = sheet.cols_values(cols, start_rowx=0, end_rowx=None)
# 获取sheet对象中第colx+1列的cell, 返回列表
cells = sheet.col(colx)
# 以切片方式获取sheet对象中第colx+1列, [start_rowx, end_rowx]区间行的数据, 返回列表
cells = sheet.col_slice(colx, start_rowx=0, end_rowx=None)
# 获取sheet对象中第colx+1行, [start_rowx, end_rowx]区间列的单元类型, 返回array.array类型
cells_array = sheet.col_types(colx, start_rowx=0, end_rowx=None)
# 单元格操作 ##############################
# 获取sheet对象中第rowx+1行, colx+1列的单元对象, 返回cell类型
cell = sheet.cell(rowx, colx)
# 获取sheet对象中第rowx+1行, colx+1列的单元数据
value = sheet.cell_value(rowx, colx)
# 获取sheet对象中第rowx+1行, colx+1列的单元数据类型
value_type = sheet.cell_type(rowx, colx)
二、Python XLWT
对 excel 表格进行编辑操作。
import xlwt
# 创建workbook对象, 如果已存在, 则读取workbook对象
workbook = xlwt.WorkBook(file) # 如果是创建, 需要指定encoding='utf-8'防止中文乱码
# 创建sheet对象, 如果已存在, 则读取sheet对象, 清空sheet内容
sheet = workbook.add_sheet('Sheet')
# 随机造数 ####################
# 写入第一行标题
sheet.write(0, 0, 'ID')
sheet.write(0, 1, 'APPLY_NO')
sheet.write(0, 2, 'LEVEL')
sheet.write(0, 3, 'CREATE_DATETIME')
sheet.write(0, 4, 'ENABLE')
index = 0 # 起始下标
cols_max = 5 # 列边界
rows_max = 1000 # 最大造数行数
for i in range(1, rows_max):
index += 1
for j in range(cols_max):
apply_no = f'XNAB{int(time.time() * 1000000)}'
status = random.randint(0, 10)
create_datetime = datetime.datetime.now().__format__('%Y-%m-%d %H:%M:%S')
enable = random.choice(['Y', 'N'])
cell_value = {
0: index,
1: apply_no,
2: status,
3: create_datetime,
4: enable
}[j]
sheet.write(i, j, cell_value)
workbook.save('test.xls') # 保存编辑内容, 如果没有这一步之前的操作将会回退
关注【嘎嘎软件测试】
搞测试,不迷路
呱呱大王本呱带你飞!
嘎嘎软件测试
将分享个人成长、团队管理、软件测试技能知识等内容,做到有思想、有观点、有深度,欢迎订阅。