【问题标题】:'str' object has no attribute“str”对象没有属性
【发布时间】:2016-07-14 13:26:33
【问题描述】:

我正在尝试在 excel 中打开一列并将其单元格中的所有值移动到列表中。

def open_excel(col, excel_file): 
   open_file = openpyxl.load_workbook(excel_file) 
   sheet_object = open_file.get_sheet_names()[0]
   cell_vals = []
   col_num = column_index_from_string(start_col)
   for cell in sheet_object.columns[col_num]: 
       cell_vals.append(str(cell.value))

运行后出现错误:

builtins.AttributeError: 'str' object has no attribute 'columns'

但我也已经导入了所有内容。

这是我导入的内容:

import openpyxl 
from openpyxl.cell import get_column_letter, column_index_from_string
import numpy as np 
import matplotlib.pyplot as plt

【问题讨论】:

  • 查看columns 作为属性被访问的位置......print(type(sheet_object))....查看sheet_object 的定义位置......调试完成。

标签: python excel attributeerror strerror


【解决方案1】:

你有一个工作表名称,一个字符串对象,分配给sheet_object

sheet_object = open_file.get_sheet_names()[0]

get_sheet_names() 返回一个字符串序列,而不是对象;它只返回self.sheetnames。您必须使用该名称来获取实际的工作表对象:

sheet_name = open_file.get_sheet_names()[0]
sheet_object = open_file[sheet_name]  # subscription takes sheet names

您可以更轻松地获取第一个活动工作表:

sheet_object = open_file.worksheets[0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-11
    • 2016-09-20
    • 2019-03-25
    • 2017-05-13
    • 2014-04-28
    • 2015-05-15
    • 2019-06-20
    • 2021-12-14
    相关资源
    最近更新 更多