Why is the iteration over this loop not adding cells in openpyxl?

拜拜、爱过 提交于 2019-12-20 03:55:12

问题


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

Then:

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

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

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

When I try:

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

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.


回答1:


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)

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


来源:https://stackoverflow.com/questions/31237229/why-is-the-iteration-over-this-loop-not-adding-cells-in-openpyxl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!