You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用openpyxl向Excel写入字典值时结果始终为0的问题求解

问题根因
  • 写入Excel的逻辑位置错误:carga_excel_sin_numeracion 函数调用放在了if判断分支外,不管当前输入是否匹配目标尺码,都会执行写入操作。只要任意一次调用时if条件不触发,初始化全为0的dict_talles就会把之前正确写入的数值覆盖为0,测试时输入结束指令N前的最后一次调用大概率触发了这个问题。
  • 字符串分割逻辑存在隐患:使用split(' ')按单个空格分割,若输入时冒号前后存在多个空格、制表符,会导致talles列表格式不符合预期,if talles[0] == (sigla + ':')条件无法命中,字典值始终保持初始的0。
  • 逻辑运算符使用不规范:while循环条件中使用了位运算符&,而非Python的逻辑与运算符and,复杂条件下会出现预期外的判断结果。
  • 字典重复初始化:dict_talles是函数内部的局部变量,每次调用pasaje_lista_sin_numeracion都会重新创建全0的字典,仅支持单次单尺码写入,多尺码场景下会丢失之前的数值。
修复方案
  1. 将Excel写入逻辑挪到if判断分支内部,仅当匹配到对应尺码、修改完字典值后再执行写入
  2. 把字符串分割改为不带参数的split(),自动处理任意空白字符,兼容输入时的多空格、制表符等场景
  3. 把while条件的&替换为and
  4. 若需要支持多尺码累计写入,将dict_talles提到函数外部作为全局变量,避免每次调用重复初始化

修改后的核心代码片段

import openpyxl

pedido_camisetas = r'test\Pedido de Camisetas de Rugby.xlsx'
wb_camisetas = openpyxl.load_workbook(pedido_camisetas, read_only=False)
ws_camisetas = wb_camisetas.active
# 多尺码场景下将字典提到全局,避免重复初始化
dict_talles={6 : 0, 8 : 0, 10 : 0, 12 : 0, 14 : 0, 16 : 0, 'S' : 0, 'M' : 0, 'L' : 0, 'XL' : 0, 'XXL' : 0, 'XXXL' : 0, 'XXXXL' : 0,}    

#Post-Conditions: obtains a list with the asked talles (sizes), given by the user.
def ingreso_talles_camiseta_sin_numeracion():
    talles = input('Pasame los talles: ')
    talles = talles.split() # 改为无参数split,自动处理任意空白
    while talles[0] != 'N' and talles[0] != 'n': # 替换&为and
        pasaje_lista_sin_numeracion(talles, '6')
        talles = input('Pasame los talles: ')
        talles = talles.split()

#Pre-conditions: receive a list of talles (sizes) and the number or letter (in this testing case just number) referred to that size ("sigla").
#Post-conditions: Assings the number of sizes its proper key into the dictionary. The unchanged keys will remain on 0. 
def pasaje_lista_sin_numeracion(talles, sigla):
    global dict_talles # 仅单尺码测试可删除这行,保留局部字典即可
    if talles[0] == (sigla + ':'):
        del talles[0]
        if sigla.isdigit():
            sigla = int(sigla)
        dict_talles[sigla] = int(talles[0])
        # 仅当修改完成后再执行写入,挪到if内部
        carga_excel_sin_numeracion(dict_talles, 6, 'D5')

# Pre: Will receive a dict with sizes and numbers, the number or letter referring to that size and the cell we want the excel to be completed
#Post: it will asing the sizes to the given cell and it will save the file
def carga_excel_sin_numeracion(diccionario, sigla, celda):
    ws_camisetas[celda] = diccionario[sigla]
    wb_camisetas.save(r'test\Pedido de Camisetas de Rugby.xlsx')

内容的提问来源于stack exchange,提问作者Luca Salluzzi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:36:01