python 如何改进每周计划系统,以创建Excel电子表格,不仅将SUN列为一天,还列出一周中的每一天?

oug3syen  于 2023-08-02  发布在  Python
关注(0)|答案(1)|浏览(86)

下面是我正在做的简单程序:

import openpyxl
from openpyxl import Workbook
from openpyxl.utils.exceptions import InvalidFileException
import webbrowser

CATEGORIES = {
    "Housing":        0.3,
    "Emergency Fund": 0.1,
    "Brokerage Account": 0.05,
    "Vacations": 0.05,
    "Entertainment": 0.08,
    "Restaurants": 0.05,
    "Clothing": 0.038,
    "Family": 0.05,
    "Christmas": 0.02,
    "Gifts": 0.02,
    "Hobbies": 0.1,
    "House Upgrades": 0.05,
    "Cable": 0.02,
    "Internet": 0.02,
    "Subscriptions": 0.02,
    "Lawn": 0.02,
    "Beauty Products": 0.02,
    "Gym Memberships": 0.02,
    "Mortgage": 0.18,
    "House Taxes": 0.05,
    "House Insurance": 0.02,
    "Electricity": 0.0235,
    "House gas": 0.02,
    "Water / Garbage": 0.02,
    "House Repairs": 0.05,
    "Other housing costs": 0.05,
    "Groceries": 0.1,
    "Vehicle Gas": 0.02,
    "Grandkids": 0.02,
    "Vehicle Taxes and Insurance": 0.05,
    "Vehicle Replacement": 0.05,
    "Oil Changes": 0.02,
    "AAA": 0.02,
    "Tires": 0.02,
    "Vehicle Repairs / Upkeep": 0.05,
    "Health Insurance Premiums": 0.1,
    "Healthcare Costs": 0.05,
    "Cell Phones": 0.05,
    "Credit Card Payments": 0.05,
    "CarPayments": 0.05,
    "Auto Insurance": 0.014
}
# Get the coffee and meal times for 5 different people for each meal
coffee_times = []
breakfast_times = []
lunch_times = []
afternoon_snack_times = []
dinner_times = []

def open_urls():
    urls = [
        "https://logon.vanguard.com",
        "https://robinhood.com",
        "https://blockfi.com",
        "https://mint.intuit.com/trends",
        "https://www.myfitnesspal.com/reports",
        "https://next.waveapps.com/",
        "https://www.ncsecu.org",
        "https://www.bankofamerica.com",
        "https://www.paypal.com",
        "https://www.advisorclient.com",
        "https://client.schwab.com",
        "https://dashboard.stripe.com",
        "https://www.buymeacoffee.com/dashboard",
        "https://www.udemy.com/",
        "https://www.linkedin.com/",
        "https://www.youtube.com/",
        "https://itunesconnect.apple.com/login",  
        "https://poe.com",
        "https://quora.com",
        "https://github.com/",  
        "https://stackoverflow.com",
        "https://nytimes.com",
        "https://wsj.com",
        "https://medium.com",
        "https://investopedia.com",
        "https://www.godaddy.com",
        "https://www.evan-gertis.com",
        "https://members.carolinas.aaa.com/login",
        "https://www.t-mobile.com/",
        "https://gourl.io/"
             
    ]
    
    for url in urls:
        webbrowser.open(url)

def prompt_user():
    top_priority = input("What is your top priority for the day? ")
    top_priority_date = input("When do you need to have this priority completed? (format: YYYY-MM-DD) ")
    second_priority = input("What is your second priority for the day? ")
    second_priority_date = input("When do you need to have this priority completed? (format: YYYY-MM-DD) ")
    third_priority = input("What is your third priority for the day? ")
    third_priority_date = input("When do you need to have this priority completed? (format: YYYY-MM-DD) ")
    advice = input("Who can you call for advice on achieving your goals? ")
    actions = input("What specific actions do you need to take to move closer to your objectives? ")
    devotional = input("Did you take 10-15 minutes for morning devotional or meditation? (yes/no) ")
    workout = input("Did you complete a 30-45 minute workout or core exercise routine? (yes/no) ")
    budget_review = input("Did you complete your weekly budget review and stick to your budget for the week (assuming an average spending amount of $176.1 per category)? (yes/no) ")
    overspending = {}
    for category in CATEGORIES:
        response = input(f"Did you overspend in {category}? If so, how much? (enter a number or '0' if not applicable) ")
        while not (response.isdigit() or response == "0"):
            response = input(f"Invalid input. Did you overspend in {category}? If so, how much? (enter a number or '0' if not applicable) ")
        overspending[category] = float(response)
    unexpected_expenses = {}
    for category in CATEGORIES:
        response = input(f"Were there any unexpected expenses that came up in {category}? If so, how much? (enter a number or '0'') ")
        while not (response.isdigit() or response == "0"):
            response = input(f"Invalid input. Were there any unexpected expenses that came up in {category}? If so, how much? (enter a number or '0') ")
        unexpected_expenses[category] = float(response)
    
    return {
        "top_priority": top_priority,
        "top_priority_date": datetime.datetime.strptime(top_priority_date, "%Y-%m-%d"),
        "second_priority": second_priority,
        "second_priority_date": datetime.datetime.strptime(second_priority_date, "%Y-%m-%d"),
        "third_priority": third_priority,
        "third_priority_date": datetime.datetime.strptime(third_priority_date, "%Y-%m-%d"),
        "advice": advice,
        "actions": actions,
        "devotional": devotional,
        "workout": workout,
        "budget_review": budget_review,
        "overspending": overspending,
        "unexpected_expenses": unexpected_expenses
    }

def calculate_budget(CATEGORIES, total_income):
    budget = {}
    for category, percentage in CATEGORIES.items():
        budget[category] = round(percentage * total_income, 2)
    return budget

def print_budget(budget):
    for category, amount in budget.items():
        print(f"{category}: ${amount}")

def main():
    try:
        workbook = openpyxl.load_workbook("budget.xlsx")
    except InvalidFileException:
        print("Invalid file format.")
        return
    sheet = workbook.active
    open_urls()
    total_income = input("What is your income? ")
    total_income = float(total_income) # convert to float
    print(f"Total Income: ${total_income}")
    budget = calculate_budget(CATEGORIES, total_income)
    print_budget(budget)
    user_input = prompt_user()
    print(user_input)
    for i in range(5):
        name = input(f"Enter the name of person {i+1}: ")
        coffee_time = input(f"Enter the best time for coffee for {name}: ")
        coffee_times.append(coffee_time)
        breakfast_time = input(f"Enter the best time for breakfast for {name}: ")
        breakfast_times.append(breakfast_time)
        lunch_time = input(f"Enter the best time for lunch for {name}: ")
        lunch_times.append(lunch_time)
        afternoon_snack_time = input(f"Enter the best time for afternoon snack for {name}: ")
        afternoon_snack_times.append(afternoon_snack_time)
        dinner_time = input(f"Enter the best time for dinner for {name}: ")
        dinner_times.append(dinner_time)

    # Create a new Excel workbook
    wb = Workbook()

     # Create a new sheet
    results_sheet = wb.create_sheet("Results")

    # Write the headers
    headers = ["Category", "Overspending", "Unexpected Expenses"]
    for col_num, header in enumerate(headers, start=1):
        results_sheet.cell(row=1, column=col_num, value=header)
    
    # Write the results
    for row_num, category in enumerate(CATEGORIES, start=2):
        results_sheet.cell(row=row_num, column=1, value=category)
        results_sheet.cell(row=row_num, column=2, value=user_input['overspending'].get(category, 0))
        results_sheet.cell(row=row_num, column=3, value=user_input['unexpected_expenses'].get(category, 0))
    
    # Save the workbook
    wb.save("results.xlsx")

    # Create sheets for each section
    coffee_sheet = wb.active
    coffee_sheet.title = "Coffee"
    breakfast_sheet = wb.create_sheet("Breakfast")
    lunch_sheet = wb.create_sheet("Lunch")
    afternoon_snack_sheet = wb.create_sheet("Afternoon Snack")
    dinner_sheet = wb.create_sheet("Dinner")

    sheets = [coffee_sheet, breakfast_sheet, lunch_sheet, afternoon_snack_sheet, dinner_sheet]

    # Save schedules in each sheet
    meal_sections = [
        {"title": "Coffee", "times": coffee_times},
        {"title": "Breakfast", "times": breakfast_times},
        {"title": "Lunch", "times": lunch_times},
        {"title": "Afternoon Snack", "times": afternoon_snack_times},
        {"title": "Dinner", "times": dinner_times},
    ]

    for sheet, section in zip(sheets, meal_sections):
        sheet.cell(row=1, column=1, value=section["title"])
        sheet.cell(row=2, column=1, value="Day")
        sheet.cell(row=2, column=2, value="Time")
        sheet.cell(row=2, column=3, value="Person")

        for day in ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"]:
            for i, time in enumerate(section["times"]):
                row = i + 3
                name = f"{meal_sections[0]['times'][i]}" # assuming coffee_times is not empty
                sheet.cell(row=row, column=1, value=day)
                sheet.cell(row=row, column=2, value=time)
                sheet.cell(row=row, column=3, value=name)

                # For Sunday, add a row break
                if day == "SUN":
                    sheet.cell(row=row+1, column=1, value="")

    # Save the workbook to a file
    wb.save("weekly_schedule.xlsx")

if __name__ == "__main__":
    main()

字符串
当前输出仅显示weekly_schedule.xslx文件中的一个。预期输出不应只显示SUN,还应显示星期一、星期二、星期三、星期四、星期五、星期六和星期日。
我该如何继续前进?

bis0qfac

bis0qfac1#

我解决了

import openpyxl
from openpyxl import Workbook
from openpyxl.utils.exceptions import InvalidFileException
import webbrowser
import datetime

CATEGORIES = {
    "Housing":        0.3,
    "Emergency Fund": 0.1,
    "Brokerage Account": 0.05,
    "Vacations": 0.05,
    "Entertainment": 0.08,
    "Restaurants": 0.05,
    "Clothing": 0.038,
    "Family": 0.05,
    "Christmas": 0.02,
    "Gifts": 0.02,
    "Hobbies": 0.1,
    "House Upgrades": 0.05,
    "Cable": 0.02,
    "Internet": 0.02,
    "Subscriptions": 0.02,
    "Lawn": 0.02,
    "Beauty Products": 0.02,
    "Gym Memberships": 0.02,
    "Mortgage": 0.18,
    "House Taxes": 0.05,
    "House Insurance": 0.02,
    "Electricity": 0.0235,
    "House gas": 0.02,
    "Water / Garbage": 0.02,
    "House Repairs": 0.05,
    "Other housing costs": 0.05,
    "Groceries": 0.1,
    "Vehicle Gas": 0.02,
    "Grandkids": 0.02,
    "Vehicle Taxes and Insurance": 0.05,
    "Vehicle Replacement": 0.05,
    "Oil Changes": 0.02,
    "AAA": 0.02,
    "Tires": 0.02,
    "Vehicle Repairs / Upkeep": 0.05,
    "Health Insurance Premiums": 0.1,
    "Healthcare Costs": 0.05,
    "Cell Phones": 0.05,
    "Credit Card Payments": 0.05,
    "CarPayments": 0.05,
    "Auto Insurance": 0.014
}
# Get the coffee and meal times for 5 different people for each meal
coffee_times = []
breakfast_times = []
lunch_times = []
afternoon_snack_times = []
dinner_times = []

def open_urls():
    urls = [
        "https://logon.vanguard.com",
        "https://robinhood.com",
        "https://blockfi.com",
        "https://mint.intuit.com/trends",
        "https://www.myfitnesspal.com/reports",
        "https://next.waveapps.com/",
        "https://www.ncsecu.org",
        "https://www.bankofamerica.com",
        "https://www.paypal.com",
        "https://www.advisorclient.com",
        "https://client.schwab.com",
        "https://dashboard.stripe.com",
        "https://www.buymeacoffee.com/dashboard",
        "https://www.udemy.com/",
        "https://www.linkedin.com/",
        "https://www.youtube.com/",
        "https://itunesconnect.apple.com/login",  
        "https://poe.com",
        "https://quora.com",
        "https://github.com/",  
        "https://stackoverflow.com",
        "https://nytimes.com",
        "https://wsj.com",
        "https://medium.com",
        "https://investopedia.com",
        "https://www.godaddy.com",
        "https://www.evan-gertis.com",
        "https://members.carolinas.aaa.com/login",
        "https://www.t-mobile.com/",
        "https://gourl.io/"
             
    ]
    
    for url in urls:
        webbrowser.open(url)

def prompt_user():
    top_priority = input("What is your top priority for the day? ")
    top_priority_date = input("When do you need to have this priority completed? (format: YYYY-MM-DD) ")
    second_priority = input("What is your second priority for the day? ")
    second_priority_date = input("When do you need to have this priority completed? (format: YYYY-MM-DD) ")
    third_priority = input("What is your third priority for the day? ")
    third_priority_date = input("When do you need to have this priority completed? (format: YYYY-MM-DD) ")
    advice = input("Who can you call for advice on achieving your goals? ")
    actions = input("What specific actions do you need to take to move closer to your objectives? ")
    devotional = input("Did you take 10-15 minutes for morning devotional or meditation? (yes/no) ")
    workout = input("Did you complete a 30-45 minute workout or core exercise routine? (yes/no) ")
    budget_review = input("Did you complete your weekly budget review and stick to your budget for the week (assuming an average spending amount of $176.1 per category)? (yes/no) ")
    overspending = {}
    for category in CATEGORIES:
        response = input(f"Did you overspend in {category}? If so, how much? (enter a number or '0' if not applicable) ")
        while not (response.isdigit() or response == "0"):
            response = input(f"Invalid input. Did you overspend in {category}? If so, how much? (enter a number or '0' if not applicable) ")
        overspending[category] = float(response)
    unexpected_expenses = {}
    for category in CATEGORIES:
        response = input(f"Were there any unexpected expenses that came up in {category}? If so, how much? (enter a number or '0'') ")
        while not (response.isdigit() or response == "0"):
            response = input(f"Invalid input. Were there any unexpected expenses that came up in {category}? If so, how much? (enter a number or '0') ")
        unexpected_expenses[category] = float(response)
    
    return {
        "top_priority": top_priority,
        "top_priority_date": datetime.datetime.strptime(top_priority_date, "%Y-%m-%d"),
        "second_priority": second_priority,
        "second_priority_date": datetime.datetime.strptime(second_priority_date, "%Y-%m-%d"),
        "third_priority": third_priority,
        "third_priority_date": datetime.datetime.strptime(third_priority_date, "%Y-%m-%d"),
        "advice": advice,
        "actions": actions,
        "devotional": devotional,
        "workout": workout,
        "budget_review": budget_review,
        "overspending": overspending,
        "unexpected_expenses": unexpected_expenses
    }

def calculate_budget(CATEGORIES, total_income):
    budget = {}
    for category, percentage in CATEGORIES.items():
        budget[category] = round(percentage * total_income, 2)
    return budget

def print_budget(budget):
    for category, amount in budget.items():
        print(f"{category}: ${amount}")

def main():
    try:
        workbook = openpyxl.load_workbook("budget.xlsx")
    except InvalidFileException:
        print("Invalid file format.")
        return
    sheet = workbook.active
    open_urls()
    total_income = input("What is your income? ")
    total_income = float(total_income) # convert to float
    print(f"Total Income: ${total_income}")
    budget = calculate_budget(CATEGORIES, total_income)
    print_budget(budget)
    user_input = prompt_user()
    print(user_input)
    for i in range(5):
        name = input(f"Enter the name of person {i+1}: ")
        coffee_time = input(f"Enter the best time for coffee for {name}: ")
        coffee_times.append(coffee_time)
        breakfast_time = input(f"Enter the best time for breakfast for {name}: ")
        breakfast_times.append(breakfast_time)
        lunch_time = input(f"Enter the best time for lunch for {name}: ")
        lunch_times.append(lunch_time)
        afternoon_snack_time = input(f"Enter the best time for afternoon snack for {name}: ")
        afternoon_snack_times.append(afternoon_snack_time)
        dinner_time = input(f"Enter the best time for dinner for {name}: ")
        dinner_times.append(dinner_time)

    # Create a new Excel workbook
    wb = Workbook()

     # Create a new sheet
    results_sheet = wb.create_sheet("Results")

    # Write the headers
    headers = ["Category", "Overspending", "Unexpected Expenses"]
    for col_num, header in enumerate(headers, start=1):
        results_sheet.cell(row=1, column=col_num, value=header)
    
    # Write the results
    for row_num, category in enumerate(CATEGORIES, start=2):
        results_sheet.cell(row=row_num, column=1, value=category)
        results_sheet.cell(row=row_num, column=2, value=user_input['overspending'].get(category, 0))
        results_sheet.cell(row=row_num, column=3, value=user_input['unexpected_expenses'].get(category, 0))
    
    # Save the workbook
    wb.save("results.xlsx")

    # Create sheets for each section
    coffee_sheet = wb.active
    coffee_sheet.title = "Coffee"
    breakfast_sheet = wb.create_sheet("Breakfast")
    lunch_sheet = wb.create_sheet("Lunch")
    afternoon_snack_sheet = wb.create_sheet("Afternoon Snack")
    dinner_sheet = wb.create_sheet("Dinner")

    sheets = [coffee_sheet, breakfast_sheet, lunch_sheet, afternoon_snack_sheet, dinner_sheet]

    # Save schedules in each sheet
    meal_sections = [
        {"title": "Coffee", "times": coffee_times},
        {"title": "Breakfast", "times": breakfast_times},
        {"title": "Lunch", "times": lunch_times},
        {"title": "Afternoon Snack", "times": afternoon_snack_times},
        {"title": "Dinner", "times": dinner_times},
    ]

    for sheet, section in zip(sheets, meal_sections):
        sheet.cell(row=1, column=1, value=section["title"])
        sheet.cell(row=2, column=1, value="Day")
        sheet.cell(row=2, column=2, value="Time")
        sheet.cell(row=2, column=3, value="Person")

        days_of_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
        for day_number, day in enumerate(days_of_week):
            for i, time in enumerate(section["times"]):
                row = i + 3 + (day_number * (len(section["times"]) + 3))
                name = f"{meal_sections[0]['times'][i]}" # assuming coffee_times is not empty
                sheet.cell(row=row, column=1, value=day)
                sheet.cell(row=row, column=2, value=time)
                sheet.cell(row=row, column=3, value=name)

    # Save the workbook to a file
    wb.save("weekly_schedule_2.xlsx")

if __name__ == "__main__":
    main()

字符串

相关问题