'str' object has no attribute

15.9k Views Asked by At

I'm trying to open a column in excel and move all the values from it's cells into a list.

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))

After I run that I get the error:

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

But I've already imported everything as well.

Here's what I've imported:

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

There are 1 best solutions below

0
On

You have a sheet name, a string object, assigned to sheet_object:

sheet_object = open_file.get_sheet_names()[0]

get_sheet_names() returns a sequence of strings, not of objects; it just returns self.sheetnames. You would have to use that name to get the actual sheet object:

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

You could more easily grab the first active work sheet with:

sheet_object = open_file.worksheets[0]