Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Randomize in tables
#5
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!')
Reply


Messages In This Thread
Randomize in tables - by mariavol - Aug-15-2022, 07:46 AM
RE: Randomize in tables - by Pedroski55 - Aug-15-2022, 10:29 AM
RE: Randomize in tables - by mariavol - Aug-15-2022, 02:36 PM
RE: Randomize in tables - by deanhystad - Aug-15-2022, 09:23 PM
RE: Randomize in tables - by Pedroski55 - Aug-15-2022, 11:30 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020