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中添加单元格?
基础教程推荐
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
