简体   繁体   English

Openpyxl将字典写入电子表格

[英]Openpyxl Write Dictionary to Spreadsheet

I'm working on a protein tracker to track the amount of protein that I've eaten today and I'm having trouble entering the values into a spreadsheet. 我正在使用蛋白质追踪器来跟踪今天食用的蛋白质量,但无法将值输入电子表格中。 I've saved the food and their associated protein values in a dictionary (total_protein_dictionary) and when I include print statements in my code, it says that the values are being entered in the sheet, but when I go to check it out in excel, there's nothing there. 我已经将食物及其相关的蛋白质值保存在字典中(total_protein_dictionary),当我在代码中包含打印语句时,它表示这些值已输入工作表中,但是当我在excel中进行检查时,那里什么都没有。 I've tried a couple different things. 我尝试了几种不同的方法。

import openpyxl
def write_values_to_spreadsheet(file, total_protein_dictionary):
"""Takes the keys and values of the total protein dictionary and puts them in the spreasheet"""
wb = openpyxl.load_workbook(file)
sheet_names = wb.sheetnames
sheet = wb.get_sheet_by_name(sheet_names[0])
print(len(total_protein_dictionary))

for next_row in range(1, len(total_protein_dictionary)+1):
    food, protein_grams = total_protein_dictionary.popitem()
    sheet.cell(column=1 , row=next_row, value=food)
    sheet.cell(column=2 , row=next_row, value=protein_grams)

    wb.save(file)

variant 2: 变体2:

def write_values_to_spreadsheet(file, total_protein_dictionary):
"""Takes the keys and values of the total protein dictionary and puts them in the spreasheet"""
wb = openpyxl.load_workbook(file)

sheet_names = wb.sheetnames
sheet = wb.get_sheet_by_name(sheet_names[0])
print(len(total_protein_dictionary))


for key in range(1, len(total_protein_dictionary)+1):
    food, protein_grams = total_protein_dictionary.popitem()
    print(food, protein_grams)
    index = str(key)

    sheet['A' + index] = food
    sheet['B' + index] = protein_grams
    wb.save(file)

Why won't it all display in my excel sheet? 为什么它们都不会显示在我的Excel工作表中? Also, what's the difference between using 另外,使用之间有什么区别

sheet_names = wb.sheetnames
sheet = wb.get_sheet_by_name(sheet_names[0])

and

wb.active

if I want to work on the first sheet? 如果我想在第一张纸上工作?

Ok so the function was working fine on its own, the problem turned out to be in my 'run' function and I was actually able to fix it. 好的,因此该函数可以正常运行,问题出在我的“运行”函数中,实际上我可以对其进行修复。 Here's the code from my updated write_values_to_spreadsheet and 'run' function. 这是我更新的write_values_to_spreadsheet和'run'函数中的代码。

def write_values_to_spreadsheet(wb, total_protein_dictionary):
"""Takes the keys and values of the total protein dictionary and puts them in the spreasheet"""
    sheet = wb.active

    print(len(total_protein_dictionary))

    for next_row in range(1, len(total_protein_dictionary)+1):

        food, protein_grams = total_protein_dictionary.popitem()
        sheet.cell(column=1 , row=next_row, value=food)
        sheet.cell(column=2 , row=next_row, value=protein_grams)

def run(file):
"""Runs the whole program"""
    wb = openpyxl.load_workbook(file) #opens the workbook at the beginning
    checks_sheet_title(wb)
    #food_protein(x) function start
    eaten_today = str(input("Did you eat any food today?\n")).lower()
    total_protein_dictionary = {} #creates dictionary that can be updated, taken as a     paramter in food_protein

    if eaten_today == "yes":
        foods_documented = False #answers the question: has all food eaten today been accounted for?
        total_protein_dictionary.update(food_protein(total_protein_dictionary)) #updates with new food
        print(total_protein_dictionary)

        while foods_documented == False:
            more_food = str(input("Did you have any more food?\n"))
            if more_food == "yes":
                total_protein_dictionary.update(food_protein(total_protein_dictionary))
                print(total_protein_dictionary)
            elif more_food == "no":
                foods_documented = True #escapes

    print("Today you've had " + str(sum(total_protein_dictionary.values())) + " grams of protein so far today.")
    write_values_to_spreadsheet(wb, total_protein_dictionary)
    wb.save(file)

The first bit of 'run' prompts the user to make the dictionary, then on line 35 calls write_values_to_spreadsheet. “运行”的第一位提示用户制作字典,然后在第35行调用write_values_to_spreadsheet。 What fixed the issue for me is that I changed write_values_to_spreadsheet to take wb as a parameter instead of file, in the process I deleted wb = openpyxl.load_workbook(file) and wb.save(file) because 'run' already had those. 对我而言,解决此问题的原因是,我更改了write_values_to_spreadsheet以将wb用作参数而不是文件,在此过程中,我删除了wb = openpyxl.load_workbook(file)和wb.save(file),因为“运行”已经有了这些文件。 I guess that they were unnecassary and causing the problem. 我认为它们是不必要的,并导致了问题。

Anyway, it's working now! 无论如何,它现在正在工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM