【Python】pandas遍历读取excel文件,修改并保存(一)

code ide and lib version:

python            2.7(64)

pycharm            2018.1.4

xlrd            1.1.0

pandas            0.23.1

play:

这个是一个读取excel表格里的接口数据,实例化为一个对象,供操作,往事把一顿操作后的结果写回到excel里,完事。

look at the code:

#!usr/bin/env python  
# -*- coding:utf-8 -*-

""" 
@author: jayzhen
@email: jayzhen_testing@163.com
@site: https://github.com/gitjayzhen
@software: PyCharm & Python 2.7
@file: RequestBuilder.py 
@time: 2018/06/27 19:13 
"""
from com.framework.utils.fileUtil.FileInspector import FileInspector
from com.framework.interface.domian.DataStruct import DataStructer
from com.framework.interface.api.HttpClient import Requester
import pandas as pd
import re


class RequestBuilder(object):

    def __init__(self):
        fc = FileInspector()
        self.filepath = None
        self.propath = None
        boolean = fc.is_has_file("接口测试用例集.xlsx")
        if boolean:
            self.filepath = fc.get_fileabspath()
            self.propath = fc.get_project_path()

    def data_mapping(self, source, obj):
        """
        将excel读取的行数据,映射成一个操作对象,共测试报告使用
        :param source: 读取的excel row
        :param obj: domain数据对象
        :return: obj
        """
        if source is None:
            return None
        if isinstance(source, tuple) and isinstance(obj, DataStructer):
                obj_attr = dir(obj)
                for i in obj_attr:
                    if i.startswith("__"):
                        continue
                    obj.__setattr__(i, source.__getattribute__(i))
        return obj

    def send_req(self, ds):
        """
        将excel中的接口数据发送出去
        :param ds: domain对象
        :return: None
        """
        if ds is None:
            return None
        req = Requester()
        resp = req.execute_request(ds.req_method, ds.req_url)
        if re.findall(ds.resp_assert, resp.text):
            ds.test_result = resp.status_code
            ds.test_notes = str(resp.headers)

    def get_sheet_table(self):
        """
        需要处理的时将excel的内容读出来和修改内容并保存
        :return:
        """
        # 读取一个excel的文本文件(当前默认时读一个文件的一个sheet页)
        ex = pd.read_excel(unicode(self.filepath, "utf8"))
        # 用pd格式化
        df = pd.DataFrame(ex)
        # 迭代器遍历sheet页里的内容
        for row in df.itertuples(name="RowData"):
            # 实例化一个数据模型对象
            ds = DataStructer()
            # 用读到的excel行数据来填充这个对象
            obj = self.data_mapping(row, ds)
            # 通过这个对象的属性值,来发起一次request请求,在请求的过程把结果及校验的数据处理完后,
            self.send_req(ds)
            print ds.__dict__
            # 接口发起后的结果写入到excel对应行的对应列中
            # 执行修改操作
            df.update(pd.Series(ds.test_result, name="test_result", index=[row.Index]))
            df.update(pd.Series(ds.test_notes, name="test_notes", index=[row.Index]))

        # 执行数据更新后的保存操作:这里有个问题就是源文件覆盖保存,会没有特定的样式,需要再升级一下
        df.to_excel(unicode(self.filepath, "utf8"))


if __name__ == "__main__":
    rb = RequestBuilder()
    rb.get_sheet_table()

整个项目暂未开源,如有想法,可以交流交流

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值