Openpyxl使用offset设置列名下方单元格值报NameError解决
报错原因
NameError: name 'offset' is not defined 由单元格偏移方法的调用语法错误导致:offset 是openpyxl库中Cell类的内置实例方法,必须通过实例对象.方法名()的点语法格式调用,不能将offset作为独立函数、把cell对象作为函数入参传入调用。
对应场景
该问题出现在如下Excel处理需求中:
- 待处理表格仅首行存在列名,其余行均为空,列结构为
table_name|column_a|column_b|column_c|column_d - 目标列名列表为
[column_a, column_c] - 逻辑要求:遍历工作表所有单元格,匹配到列表内的列名时,在列名正下方的单元格写入
NULL值
初始编写的错误实现代码:
for row in worksheet.rows: for cell in row: if cell.value in col_names: cell(offset(row=1, column=0)).value='NULL'
运行代码抛出的错误信息:
NameError: name 'offset' is not defined
修复方法
调整偏移方法的调用格式即可,将错误行的cell(offset(row=1, column=0)).value修改为cell.offset(row=1, column=0).value。
修正后可正常运行的完整代码:
for row in worksheet.rows: for cell in row: if cell.value in col_names: cell.offset(row=1, column=0).value='NULL'
内容的提问来源于stack exchange,提问作者OskarF
相关产品推荐
相关产品推荐

