我正在将openpyxl与python 3配合使用,并且试图创建一个脚本,该脚本为十个不同的用户创建一个随机的用户名。然后,我试图获取将每个用户名添加到excel文件中特定列的脚本。
这是我目前的代码:
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')
该函数创建一个随机用户名,但是我无法获得分配给单元格的用户名,Python告诉我未定义“名称”。
我已经尝试过了:
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')
,这会将用户名添加到单元格E1中,但仅将E1如预期的那样添加。
我无法在E列中将用户名从第1行分配到第10行。我已经尝试过使用for循环,但是我还没有开始使用它,我不确定这是否可行。希望我的解释足够好!