使用openpyxl使用随机生成的用户名将数据写入特定列

时间:2019-05-03 23:18:38

标签: python excel python-3.x openpyxl

我正在尝试使用openpyxl创建一个脚本,该脚本可以使用随机生成的用户名自动填充excel文件中的特定列。这是我目前的代码:

import random
import openpyxl

path = "E:\\Desktop\\"

wb = openpyxl.load_workbook('names.xlsx')
sheet = wb.active

def random_names():
    for x in range (0, 9):
        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]

list = [random_names()]

for row in sheet.iter_rows(min_row=1, max_col=5, max_row=2):
    for cell in row:
        sheet.append(list)

wb.save('usernames.xlsx')

Example of excel file

我不确定是否应在此处使用iter_rows。我尝试使用诸如ws ['C1':'C8']之类的单元格,但是没有用。基本上,我想使用random_names函数用随机用户名填充单元格C1至C8。

我们将不胜感激! (对不起,如果我回答迟钝)

1 个答案:

答案 0 :(得分:0)

现在,您的函数未返回任何内容。像这样尝试:

def random_names():
    names = list()
    for x in range (0, 9):
        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]
        names.append(name)
    return names    

list = random_names()