Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

openpyxl - Finding error python

If someone could aid me in finding my flaw, what I want the script to do is every minute a different random number is appended to the rows. The result I am getting just gives me the same number down the rows.

from openpyxl import Workbook
from openpyxl import load_workbook
import random
import schedule     
import time
import datetime     

def create_excel(info, info2):
    wb = Workbook()

    ws = wb.active

    n = 1
    ws.title = 'Test ' + str(n)

    ws['A1'] = 42

    wb.save('sample.xlsx')

    while n < 4:
        wb = load_workbook('sample.xlsx')
        ws = wb.active
        ws.append([info, info2])
        n += 1
        wb.save('sample.xlsx')


def main():
    print('Starting program now....')
    int = random.randint(55, 99)
    int2 = random.randint(1, 50)
    excel(int, int2)
    print('Finished program.')


m = 1
schedule.every(1).minute.do(main)
while m < 4:
    schedule.run_pending()
    time.sleep(60)
    m += 1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is with the line ws.append([info, info2]) which appends the same two values each time.

To append a new pair of integers on each occurrence of your while loop, you could implement a new function that generates a new pair of random integers.

This would work:

def generate_random_number():
    int1 = random.randint(55, 99)
    int2 = random.randint(1, 50)
    return int1, int2

def create_excel():
    wb = Workbook()
    ws = wb.active
    n = 1
    ws.title = 'Test ' + str(n)
    ws['A1'] = 42
    wb.save('sample.xlsx')
    while n < 4:
        wb = load_workbook('sample.xlsx')
        ws = wb.active
        ws.append(generate_random_number())
        n += 1
        wb.save('sample.xlsx')

def main():
    print('Starting program now....')
    create_excel()
    print('Finished program.')

m = 1
schedule.every(1).minute.do(main)
while m < 4:
    schedule.run_pending()
    time.sleep(60)
    m += 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...