为什么这个循环的迭代没有在openpyxl中添加单元格?

2023-10-19Python开发问题
3

本文介绍了为什么这个循环的迭代没有在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中添加单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11