# -*- coding: utf-8 -*-
# @__author__:choppa
# @DATA 2021/8/23
import xlrd
from xlutils.copy import copy
from tools import path_handle
def readExcel(exceldir, sheet_index):
"""
根据表格的表单名,以list格式返回表单的数据
:param exceldir: 表格路径
:param sheet_index: 表单名
:return:
"""
# 打开工作薄,加formatting_info= True 表示保留文件格式,但必须为xls,表格有内容时,切记一定加上
workdBook = xlrd.open_workbook(exceldir, formatting_info=True)
# 获取工作薄中的所有表单
# workdBook.sheet_names()
# 以下标名查找表单,如果需要批量写入数据建议用by_index,方便循环取值
workSheet = workdBook.sheet_by_index(sheet_index)
relist = []
# 循环从第二列开始循环,循环所有列
for one in range(1, workSheet.nrows):
# 判读是否有空值列
if workSheet.row_values(one)[0] != '':
# 将非空列添加进list
relist.append(workSheet.row_values(one))
# 返回list
return relist
def copy_excle(exceldir):
"""
复制表格
:param exceldir: 表格路径
:return:
"""
# 打开工作薄
workBook = xlrd.open_workbook(exceldir, formatting_info=True)
# 复制表格,要选择copy(wb)
newWokrBook = copy(workBook)
return newWokrBook
if __name__ == '__main__':
res = readExcel(path_handle.xls_dir, 0)
# 打开表单,获取表单数据,使用变量保存要复制的值,循环每一行的值,将每一行要复制的值
# 源文件先备份,设置新的地址处理表格,如果发生错误可以将备份文件再备份,确保至少有一份备份文件是源文件
# 复制表格,返回的是一个复制的工作薄
nb = copy_excle(path_handle.new_dir)
# 循环取表单,使用get_sheet,其他函数可能会出问题
for onesheet in range(0, 5):
# 获取其中一个表单的数据
nsheet = nb.get_sheet(onesheet)
# 从原表中取要复制到新表的数据
inText = readExcel(path_handle.xls_dir, onesheet)
# print(inText)
# 查看表单内每条数据的长度
# print(len(inText))
# 循环每条数据
for i in range(0, len(inText)):
# 从旧表的当前表单,当前列中的目标数据,给到one 这个变量,
# inText,表示表单每行数据组成的列表,每条再组成新的列表,i表示取出每列的数据,
# 表示取第i列的数据的第一个数qr4
one = inText[i][1]
# 写入到新表中,行的第0行是表头,所以从第一行开始写入,i+1是行的值,12是列的值
nsheet.write(i + 1, 12, one)
#写入完成保存工作薄
nb.save(path_handle.new_dir)
print(f'\033[41;33;1m数据已写入{len(inText)}\033[0m')
输入结果:
数据已写入6
数据已写入16
数据已写入23
数据已写入8
数据已写入4
查看效果:
已将用例编号成功依次写入到实际结果中