2016-07-14 114 views
-2

我想在excel中打開一列,並將它的單元格中的所有值移動到列表中。'str'對象沒有任何屬性

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 
+3

看看那裏'columns'被作爲訪問屬性....'print(type(sheet_object))'....查看'sheet_object'的定義位置....調試完成。 – miradulo

回答

2

你有表名稱,一個String對象,分配給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] 
+0

@MartijnPieters謝謝你的工作 – Sasha

相關問題