Duppie Duppie - 7 months ago 25
Python Question

write the output of a function to an Excel cell

I'm trying to write the output of a user defined function to cell in Excel

This works:

wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
sheet.cell(row=(LastRow+1),column=2).value = random.randint(1,100)
wb.save('example.xlsx')


But this does not:

def reader1():
random.randint(1,100)

wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
sheet.cell(row=(LastRow+1),column=2).value = reader1()
wb.save('example.xlsx')


I've tried it various ways, but cannot get it to work.
Any help would be appreciated, including feedback on the formatting of this post (my first).

Thanks

Answer

You're not returning anything from your function, you need to return the value of you random.randint to have the column update it's value. By default a function returns None

def reader1():

     return random.randint(1,100)
Comments