I'm using openpyxl with python 3 and I'm trying to create a script that creates a random username for ten different users. Then I'm trying to get the script to add every username to a specific column in an excel file.
This is my code at the moment:
import random
import openpyxl
path = "E:\\Desktop"
wb = openpyxl.load_workbook('python.xlsx')
sheet = wb.active
def name_generator():
color = ["Red", "Green", "Blue", "White", "Black", "Yellow", "Purple", "Orange", "Pink"]
animal = ["Cat", "Dog", "Snake", "Mouse", "Tiger", "Leopard", "Moose", "Wolf", "Bear"]
number = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"]
randomColor = random.randrange(0, len(color))
randomAnimal = random.randrange(0, len(animal))
randomNumber = random.randrange(0, len(number))
name = "Username: " + color[randomColor] + animal[randomAnimal] + number[randomNumber]
sheet['E1':'E10'] = name
wb.save('newpython.xlsx')
The function creates a random username but I can't get the username assigned to the cells, Python tells me that "name" is not defined.
I've tried this:
import random
import openpyxl
path = "E:\\Desktop"
wb = openpyxl.load_workbook('python.xlsx')
sheet = wb.active
color = ["Red", "Green", "Blue", "White", "Black", "Yellow", "Purple", "Orange", "Pink"]
animal = ["Cat", "Dog", "Snake", "Mouse", "Tiger", "Leopard", "Moose", "Wolf", "Bear"]
number = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"]
randomColor = random.randrange(0, len(color))
randomAnimal = random.randrange(0, len(animal))
randomNumber = random.randrange(0, len(number))
name = "Username: " + color[randomColor] + animal[randomAnimal] + number[randomNumber]
sheet['E1'] = name
wb.save('newpython.xlsx')
and that adds the username to the cell E1, but only E1 as expected.
I'm having trouble assigning the usernames from row 1 to row 10 in the E column. I've tried using a for loop but I haven't got it working yet and I'm not sure if that's the way to go. Hopefully my explanation is good enough!
Aucun commentaire:
Enregistrer un commentaire