pyhton3读取和写入Excel

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31524409/article/details/88391731

python可以读取和编辑Excel文件。读取和编辑Excel文件在软件测试中具有非常大的作用,可以将读写excel与接口测试结合使用,大大节省测试时间和简化测试步骤。

使用python读取Excel:

# coding=utf-8
"""
调用read_and_save_cols_excel()
读取表格示例:
a 1
b 2
c 3
d 4

读取后s0中第一列数据: a b c d
读取后s1中第一列数据: 1 2 3 4
"""
import xlrd


class ReadExcel(object):
    # 初始化
    def __init__(self, path):
        self.path = path

    # 读取excel中的数据,并将数据按列存储到列表s0,s1中
    # s0中存储测试用例,s1中存储测试用例解释
    def read_and_save_cols_excel(self):
        # 读取测试用例
        data = xlrd.open_workbook(self.path)
        table = data.sheet_by_index(0)
        # ncols存储表格中数据的列数
        ncols = table.ncols

        # 按列存储excel数据到列表s1中
        s0 = []
        title0 = table.row_values(0)
        for i in range(0, ncols, 2):
            s = table.col_values(i)[1:]
            s0.append(s)
        # 按列读取excel测试用例的解释
        s1 = []
        for i in range(1, ncols, 2):
            ss = table.col_values(i)[1:]
            s1.append(ss)

        return s0, s1, title0


    # 读取excel中的数据,并将数据按行存储到列表s2中
    def read_and_save_rows_excel(self):
        # 读取测试用例
        data = xlrd.open_workbook(self.path)
        table = data.sheet_by_index(0)
        # nrows存储表格数据的行数
        nrows = table.nrows

        # 按行存储excel数据到列表s1中
        s2 = []
        title = table.row_values(0)
        for i in range(nrows):
            s = table.row_values(i)[0:]
            s2.append(s)

        return s2


# 测试代码
'''
# ReadExcel(读取文件位置)
excel = ReadExcel("../original-data/data_origin/1.xlsx")
s0, s1 = excel.read_and_save_cols_excel()
print(s0, s1)

excel2 = ReadExcel("../original-data/data_origin/1.xlsx")
s2 = excel2.read_and_save_rows_excel()
print(s2)
'''

读取excel后,我们要将读取数据再写入excel中

# coding=utf-8

import xlwt


class Writedata(object):
    # 将数据写入excel中
    def data_write(self, save_path, datas):
        book = xlwt.Workbook(encoding="utf-8")
        sheet = book.add_sheet('Sheet1', cell_overwrite_ok=True)
        # 将数据写入第i行,第j列
        i = 0
        for data in datas:
            for j in range(len(data)):
                sheet.write(i, j, data[j])
            i += 1
        book.save(save_path)


'''
s =[[1,2],[0]]
W = Writedata()
# data_write(excel存放位置, excel中写入的数据来源)
W.data_write("../reports/data_origin/1.xls", s)
'''

猜你喜欢

转载自blog.csdn.net/qq_31524409/article/details/88391731