Aug-15-2022, 11:30 PM
(This post was last modified: Aug-15-2022, 11:38 PM by Pedroski55.)
Are you starting with an Excel file? If so, you could do it like this:
import openpyxl import random path2XL = '/home/pedro/myPython/openpyxl/random_data.xlsx' wb = openpyxl.load_workbook(path2XL) ws = wb.active sheets = wb.sheetnames # need some names and cities to choose from names = ['Jack', 'Jill', 'Jane', 'John', 'Jennifer', 'Joseph', 'Jemma', 'Jesus'] cities = ['泰州', '上海', '杭州', '北京', '南京', '兰州', '昆明', '广州', '西安'] # assume row 1 contains column headers, so start in row 2 # this will put random values in the first 3 columns # you could loop through the columns too # maxCol = wb[sheet].max_column for sheet in sheets: maxRow = wb[sheet].max_row # add 1 to maxRow or you won't get the last row for rowNum in range(2, ws.max_row + 1): wb[sheet].cell(row=rowNum, column=1).value=random.choice(names) wb[sheet].cell(row=rowNum, column=2).value=random.randint(1, 500) wb[sheet].cell(row=rowNum, column=3).value=random.choice(cities) savename = 'random_data2.xlsx' savepath = '/home/pedro/myPython/openpyxl/' wb.save(savepath + savename) print('All done!')