51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 2630|回复: 3

[原创] 如何用python3自动随机生成Excel文件内容

[复制链接]
  • TA的每日心情
    奋斗
    2018-9-1 14:58
  • 签到天数: 2 天

    连续签到: 1 天

    [LV.1]测试小兵

    发表于 2018-9-1 14:04:32 | 显示全部楼层 |阅读模式
    本帖最后由 a305634841 于 2018-9-1 15:02 编辑

    首先来看效果图
    文件命名

    文件内容

    代码说明如下
    1. import xlrd
    2. import xlwt
    3. from my_framework.log import Logger
    4. import time,os
    5. import random
    6. # create a logger instance
    7. logger = Logger(logger="file_process").getlog()
    8. class file_process():
    9.     """封装操作excel的方法"""

    10.     # 获取某一页sheet对象
    11.     def create_excel_file(self):
    12.         da = time.strftime("%Y-%m-%d/%H-%M-%S", time.localtime())
    13.         self.da_a = str(da.split('/')[0])
    14.         self.da_b = str(da.split('/')[1])
    15.         filename = "case_import"+(self.da_a+'-'+self.da_b).replace('-','.')+".xls"
    16.         excel_path = os.path.dirname(os.path.abspath('.')) + '\config_file\case_import'
    17.         self.ecl =os.path.join(excel_path,filename)

    18.         book = xlwt.Workbook(encoding = 'utf-8')
    19.         self.sheet1 = book.add_sheet('Sheet 1',cell_overwrite_ok = True)
    20.         self.title = [u'进件号',u'批次号',u'批次名称',u'产品名称',u'贷款机构',u'产品类型',u'姓名',u'身份证',u'手机',u'年龄',u'性别'u'帐号',
    21.                 u'卡号',u'逾期天数',u'账龄',u'手别'        ,u'最新欠款金额',u'委案金额',u'委案时间',u'退案时间',u'最近一次进入催收日期',
    22.                  u'额度',u'案件地区',u'币种',u'开户行',u'账单日',u'开卡日期',u'是否分期',u'分期情况',u'本金',u'利息',u'违约金',
    23.                  u'最低还款',u'委案最低还款额',u'争议金额',u'争议后金额',u'服务费',u'超限费',u'累计还款',u'委前最后付款额',u'委前最后付款日',
    24.                 u'案件备注',u'家庭地址',u'家庭电话',u'公司名称',u'公司电话',u'公司地址',u'常用地址',u'账单地址',u'邮政编码',u'其他地址',
    25.                  u'QQ',u'微信',u'支付宝',u'邮箱',u'联系人1姓名',u'联系人1关系',u'联系人1电话',u'联系人2姓名',u'联系人2关系',u'联系人2电话',
    26.                  u'联系人3姓名',u'联系人3关系',u'联系人3电话']

    27.         batch_code = ['SZ-GF-2018-06-20','SZ-GF-2018-06-20','SZ-GF-2018-06-20','SZ-GF-2018-06-20','SZ-GF-2018-06-20','SZ-GF-2018-06-20',
    28.                       'SZ-GF-2018-06-20','SZ-GF-2018-06-20']
    29.         commit_money = ['255','452','1223','452','52']
    30.         self.commit_date = [self.da_a]
    31.         latest_debt_money = ['255','452','1223','452','52']
    32.         self.limit_date = ['2019-09-01','2019-05-01','2019-08-21','2019-02-01','2019-12-01','2019-09-25','2019-09-19',]
    33.         self.product_type = ['信贷','消费金融','信用卡']
    34.         self.borrower_idnumber = ['422325198908151539','620503198108111211','360103198904054718']
    35.         self.borrower_phone = ['13686821736']
    36.         self.loan_institution = ['天天测试银行']


    37.         self.write_data(self.title,0,line=1)#标题内容和格式写入


    38.         # 数据导入的条数
    39.         data_num = 6
    40.         # 进件号写入
    41.         bill_code = self.create_data_billcode(data_num)#获取5个随机字符
    42.         j = self.title_local(u'进件号')
    43.         self.write_data(bill_code, j, line=0)#对第一列进行写入,写入字段存放在lrst中
    44.         #批次号写入
    45.         batch_codes = self.create_data(batch_code,data_num)
    46.         a = self.title_local(u'批次号')
    47.         self.write_data(batch_codes, a, line=0)
    48.         #委案金额写入
    49.         commit_moneys = self.create_data(commit_money, data_num)
    50.         a = self.title_local(u'委案金额')
    51.         self.write_data(commit_moneys, a, line=0)
    52.         #最新欠款金额写入
    53.         latest_debt_moneys = self.create_data(latest_debt_money, data_num)
    54.         a = self.title_local(u'最新欠款金额')
    55.         self.write_data(latest_debt_moneys, a, line=0)
    56.         #其它固定写入
    57.         commit_dates, limit_dates, product_types, borrower_idnumbers, borrower_phones, loan_institutions = self.only_create_data(data_num)
    58.         #委案时间写入
    59.         aa = self.title_local(u'委案时间')
    60.         self.write_data(commit_dates, aa, line=0)
    61.         #退案时间写入
    62.         bb = self.title_local(u'退案时间')
    63.         self.write_data(limit_dates, bb, line=0)
    64.         #产品类型写入
    65.         cc = self.title_local(u'产品类型')
    66.         self.write_data(product_types, cc, line=0)
    67.         #身份证写入
    68.         dd = self.title_local(u'身份证')
    69.         self.write_data(borrower_idnumbers, dd, line=0)
    70.         #手机号写入
    71.         ee = self.title_local(u'手机')
    72.         self.write_data(borrower_phones, ee, line=0)
    73.         #贷款机构写入
    74.         ff = self.title_local(u'贷款机构')
    75.         self.write_data(loan_institutions, ff, line=0)


    76.         #姓名写入
    77.         i = self.title_local(u'姓名')
    78.         brrower_name = self.create_data_name(data_num)  # 获取5个随机字符
    79.         self.write_data(brrower_name, i, line=0)
    80.         book.save(self.ecl)
    81.         return filename
    82.     def write_data(self,lst,num,line=0):
    83.         """

    84.         :param lst: 写入的字段内容的列表
    85.         :param num: num来控制写入的是固定第几行第几列
    86.         :param line: 判断写入的是一行还是一列
    87.         :return: none
    88.         """
    89.         if line == 0:
    90.             for i,item in enumerate(lst):
    91.                 self.sheet1.write(i+1, num, item)
    92.         else:
    93.             for i,item in enumerate(lst):
    94.                 self.sheet1.write(num, i, item)
    95.     def title_local(self,str):
    96.         for i, item in erate(self.title):
    97.             if item == str:
    98.                 return i

    99.     #进件号生成的随机算法
    100.     def create_data_billcode(self,number):
    101.         lrst=[]
    102.         la = ['SZ','PH','HW','KL','WE','TY','DH','Z','H','W','L','E','Y','Q','SZK',
    103.               'PHK','HWK','KLK','WEK','TYK','DHK','SRZ','PRH','HRW','KRL','WRE','TRY',
    104.               'DRH','SLZ','PLH','HLW','KLL','WLE','TLY','DLH','SZL','PHL','HWL','KLL','WEL','TYL','DHL']
    105.         for a in range(1,number+1):
    106.             i = str(random.randint(0, 10000))
    107.             j = random.choice(la)
    108.             ha = j + '-' + self.da_a + '-' + i
    109.             lrst.append(ha)
    110.         return lrst
    111.     #姓名生成的随机算法
    112.     def create_data_name(self,number):
    113.         lrst = []
    114.         la = ['张', '周', '吴', '谢', '李', '高', '汤','曹', '陈', '欧阳', '慕容', '黄', '袁', '吕']
    115.         lb = ['具', '国', '暮', '各', '色', '形', '者','换', '与', '欧', '各', '力', '固', '体',
    116.                                     '为', '而', '尔', '风', '哦',
    117.               '形', '黯', '器', '个', '昂', '瘦', '力', '刻', '他']
    118.         lc = ['深', '和', '落', '省', '彩', '呈', '的','谎', '和', '妔', '给', '彩', '呈', '的',
    119.                                 '框', '和', '量', '为', '强',
    120.               '而', '的', '及', '和', '联', '给', '肉', '开', '费']
    121.         for a in range(1, number+1):
    122.             i = random.choice(la)
    123.             j = random.choice(lb)
    124.             k = random.choice(lc)
    125.             ha = i + j + k
    126.             lrst.append(ha)
    127.         return lrst

    128.     #其它数据生成算法
    129.     def create_data(self,la,number):
    130.         """

    131.         :param la: 随机数列
    132.         :param number: 生成几条数据
    133.         :return: 数据写集合
    134.         """
    135.         lrst = []
    136.         for a in range(1, number+1):
    137.             i = random.choice(la)
    138.             j = str(random.randint(0, 1000))
    139.             ha = i+j
    140.             lrst.append(ha)
    141.         return lrst
    142.     def only_create_data(self,data_num):

    143.         commit_dates = []
    144.         limit_dates = []
    145.         product_types = []
    146.         borrower_idnumbers = []
    147.         borrower_phones = []
    148.         loan_institutions = []
    149.         latest_debt_moneys = []
    150.         for b in range(1,data_num+1):
    151.             aa = random.choice(self.commit_date)
    152.             bb = random.choice(self.limit_date)
    153.             cc = random.choice(self.product_type)
    154.             dd = random.choice(self.borrower_idnumber)
    155.             ee = random.choice(self.borrower_phone)
    156.             ff = random.choice(self.loan_institution)
    157.             commit_dates.append(aa)
    158.             limit_dates.append(bb)
    159.             product_types.append(cc)
    160.             borrower_idnumbers.append(dd)
    161.             borrower_phones.append(ee)
    162.             loan_institutions.append(ff)
    163.         return commit_dates,limit_dates,product_types,borrower_idnumbers,borrower_phones,loan_institutions

    164.     #将不是今天生成的文件删除
    165.     def clear_file(self):

    166.         da = time.strftime("%Y.%m.%d/%H-%M-%S", time.localtime())
    167.         da_a = str(da.split('/')[0])
    168.         path = os.path.dirname(os.path.abspath('.')) + '\config_file\case_import'
    169.         lrst = []
    170.         for file in os.listdir(path):
    171.             if da_a not in file:
    172.                 lrst.append(file)
    173.         if len(lrst) == 0:
    174.             logger.info("没有需要删除的历史文件")
    175.         else:
    176.             for file in lrst:
    177.                 os.remove(os.path.join(path,file))
    178.     #注意返回的了lsrt是包含标题的
    179.     def get_data(self,module):
    180.         lsrt = []
    181.         line = self.title_local(module)
    182.         ExcelFile = xlrd.open_workbook(self.ecl)
    183.         sheet = ExcelFile.sheet_by_index(0)
    184.         lsrt = sheet.col_values(line)#module列内容
    185.         return lsrt


















    186. if __name__ == '__main__':
    187.     a=file_process()
    188.     a.create_excel_file()
    189.     a.clear_file()
    190.     a.get_data(u'姓名')
    复制代码
    软件测试学习资料
    百度阅读:
    接口测试
    UI、功能测试

    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有帐号?(注-册)加入51Testing

    x
    回复

    使用道具 举报

    该用户从未签到

    发表于 2018-9-1 16:58:23 | 显示全部楼层
    此帖仅作者可见

    使用道具 举报

    该用户从未签到

    发表于 2018-9-1 16:58:41 | 显示全部楼层
    此帖仅作者可见

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-4-19 09:26 , Processed in 0.073902 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表