python生成excel測試數據


  在功能測試時,經常會測到excel文件導入導出的功能,導入與導出時,需要測試系統單次導入大批量數據時是否正常,

如果系統承受不起太大的數據導入,則需要開發限制單次導入的數量,以防止系統服務異常。大量的數據手工寫太過於耗時耗力,

所以,今天用python寫了一個生產excel測試數據的腳本,用於以后測試類似功能時,生產測試數據使用。

  主要實現的功能是:

  1、自定義生產數據的行數;

  2、列數自定義;

  3、每列自定義是固定值、拼接自增長、隨機值;

代碼如下:

from openpyxl import Workbook
from openpyxl import load_workbook
import os
import random

files=r'C:\Users\Administrator\Desktop\test\testdata.xlsx' #生成測試數據文件地址
total=50 #寫入文件的總行數為total-1
columns_list=[{0:'liuwq'},{1:[1501344,1314368,1369189]},{2:[1,2,3]}]
#寫入的對應列內容,如columns_list[0]為第一列的內容,olumns_list[1]為第二列的內容;
#columns_list[n]如果key是0,則value直接寫入excel中;
# 1則取value的(list的)其中一個值,並拼接4位數字寫入excel中;
# 2則隨機取value的一個值寫入excel;

def WriteDataInExcel(files,columns_list,total):
if not os.path.exists(files):
wb = Workbook()
ws=wb.active
count_write=0
while True:
if count_write==total:
break
for i in range(2,total+1):
count_write=i
tails=str('0'*(4-len(str(i-1)))+str(i-1))
for idx,head in enumerate(columns_list,1):
if list(head.keys())[0]==1:
for hd in head[1]:
data=str(hd)+tails
if isinstance(hd,(int,float)):
ws.cell(row=i, column=idx, value=int(data))
else:
ws.cell(row=i, column=idx, value=data)
elif list(head.keys())[0]==0:
ws.cell(row=i, column=idx, value=head[0])
elif list(head.keys())[0]==2:
data=random.choice(head[2])
ws.cell(row=i, column=idx, value=data)
wb.save(files)
else:
wb=load_workbook(files)
ws=wb.active
count_write=0
while True:
if count_write==total:
break
for i in range(2,total+1):
count_write=i
tails=str('0'*(4-len(str(i-1)))+str(i-1))
for idx,head in enumerate(columns_list,1):
if list(head.keys())[0]==1:
for hd in head[1]:
data=str(hd)+tails
if isinstance(hd,(int,float)):
ws.cell(row=i, column=idx, value=int(data))
else:
ws.cell(row=i, column=idx, value=data)
elif list(head.keys())[0]==0:
ws.cell(row=i, column=idx, value=head[0])
elif list(head.keys())[0]==2:
data=random.choice(head[2])
ws.cell(row=i, column=idx, value=data)
wb.save(files)


if __name__=="__main__":
WriteDataInExcel(files, columns_list, total)

生產的文件結果:

 

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM