问题描述
给出以下内容作为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]]
我想从下面的字典中将值添加到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:没有第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中添加单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!