Why is the iteration over this loop not adding cells in openpyxl?(为什么这个循环的迭代没有在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中添加单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么这个循环的迭代没有在openpyxl中添加单元格?
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
