0

i am trying to store one column in a single variable.but I cant

code

import openpyxl
wb = openpyxl.load_workbook("coordinates.xlsx")  
sh2 = wb['sheet2']
sh1 = wb['sheet1']
x1 = (wb['sheet2'].columns["B"]).values
print(x1)

error

 x1 = (wb['sheet2'].columns["B"]).values
TypeError: 'generator' object is not subscriptable

Process finished with exit code 1

why does this happen? is there any other way to store the entire data of single column in one variable?

James Z
  • 12,209
  • 10
  • 24
  • 44
  • Does this answer your question? ["'generator' object is not subscriptable" error](https://stackoverflow.com/questions/6288016/generator-object-is-not-subscriptable-error) – politinsa Mar 23 '21 at 23:38

2 Answers2

1

Try this:

import openpyxl
wb = openpyxl.load_workbook("coordinates.xlsx")  
sh2 = wb['sheet2']
sh1 = wb['sheet1']['B']
x1 = [i.value for i in sh1]
print(x1)
Dharman
  • 30,962
  • 25
  • 85
  • 135
hod
  • 750
  • 7
  • 21
0

https://stackoverflow.com/a/66772758/10163595 gives you the specific answer you need. However by way of explanation, wb['sheet2'].columns is a generator object and can not be given a subscript.

You can use it as follows to access the individual columns and then cells:

for column in wb["sheet2"].columns:
    for cell in column:
        print(cell.value)

The column variable above is storing the entire content of a single column during each loop/iteration. The cell variable is storing the content of a single cell and you use the value property to access the data stored in each cell.

You could alternatively use the iter_cols() method to iterate through each column.

Greg Cowell
  • 677
  • 5
  • 16
  • i want to store one column in one variable and a second column in the second variable.iter_cols I have choose range that is min col and max col. in my case there is no min col and max col because there is a particular column. can you please guide a little? –  Mar 24 '21 at 05:39
  • It's the same procedure as shown in the other answer. To store column A in a variable: "column_a = wb['sheet1']['A']". To store column B in a variable: "column_b = wb['sheet1']['B']". – Greg Cowell Mar 25 '21 at 00:56