为什么这个循环的迭代没有在openpyxl中添加单元格? [英] Why is the iteration over this loop not adding cells in openpyxl?

查看:32
本文介绍了为什么这个循环的迭代没有在openpyxl中添加单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将以下内容作为 xlsx roi.xlsx 的第一页的内容:

Given the following as the contents of the first sheet of an xlsx roi.xlsx:

然后:

wb = load_workbook('roi.xlsx', data_only=True)
ws=wb.worksheets[0]
keynames = [i.value for i in ws.columns[0]]

我想将 values 从以下字典添加到 B 列:

I want to add values into column B from the following dict:

mydict = {'carnival': 2, 'festival': 3}

当我尝试时:

for k, v in mydict.items():
    keyPosition = keynames.index(k)
    ws.cell(row = keyPosition, column = 2).value = v

我最终得到一个新列 B,但整个值为空,AND 当我在使用 wb.save 保存文件后重新打开文件时,Excel 无法打开文件,因为它已损坏.

I end up with a new column B, but empty values throughout, AND when I go to re-open the file after saving it with wb.save, Excel can't open the file because it is corrupted.

推荐答案

我认为问题是您使用 keynames 的索引存储在 B 列中,索引从 0 开始,但是B 列没有任何 0 行.理想情况下,您应该得到 - openpyxl.utils.exceptions.CellCoordinatesException: There is no row 0 (B0)

I think the issue is that you are using the index of keynames to store in the B column, index starts at 0 , but column B does not have any 0 row. You should ideally be getting - openpyxl.utils.exceptions.CellCoordinatesException: There is no row 0 (B0)

改用此代码(开始更改第 1 行的值,而不是 0)-

Try this code instead (to start changing values at row 1,instead of 0) -

for k, v in mydict.items():
    keyPosition = keynames.index(k)
    ws.cell(row = keyPosition + 1, column = 2).value = v

这篇关于为什么这个循环的迭代没有在openpyxl中添加单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆