How can we use iter_rows () in the openpyxl Python package?

I am using the openpyxl package in Python(Canopy) to use excel files. We have this tutorial at this link: LINK

 you can also use the openpyxl.worksheet.Worksheet.iter_rows() method: >>> tuple(ws.iter_rows('A1:C2')) ((<Cell Sheet1.A1>, <Cell Sheet1.B1>, <Cell Sheet1.C1>), (<Cell Sheet1.A2>, <Cell Sheet1.B2>, <Cell Sheet1.C2>)) >>> for row in ws.iter_rows('A1:C2'): ... for cell in row: ... print cell <Cell Sheet1.A1> <Cell Sheet1.B1> <Cell Sheet1.C1> <Cell Sheet1.A2> <Cell Sheet1.B2> <Cell Sheet1.C2> 

How can we import the openpyxl.worksheet.Worksheet.iter_rows() method in python? I used this code:

 import openpyxl as op ms = op.load_workbook('mtest.xlsx') ws = ms.active op.worksheet.Worksheet.iter_rows() 

This code returns:

 type object 'Worksheet' has no attribute 'iter_rows' 

What is the problem?

+6
source share
1 answer

As shown in the tutorial , you need to call the iter_rows method on the iter_rows instance, for example:

 >>> for row in ws.iter_rows('A1:C2'): ... for cell in row: ... print cell 

or

 >>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2): ... for cell in row: ... print(cell) <Cell Sheet1.A1> <Cell Sheet1.B1> <Cell Sheet1.C1> <Cell Sheet1.A2> <Cell Sheet1.B2> <Cell Sheet1.C2> 

As indicated in the error message, you call it by type Worksheet , which will not work; it must be called on the object:

 op.worksheet.Worksheet.iter_rows() # wrong 

See also this example in another answer.

For older versions of openpyxl, you may need to enable iterators when loading your book - see this thread . This is not required for later versions.

Here is a complete example that I just tested in Python REPL (with openpyxl 1.8.3):

 >>> import openpyxl as op >>> wb = op.load_workbook('/tmp/test.xlsx', use_iterators=True) >>> ws = wb.active >>> for row in ws.iter_rows(): ... for cell in row: ... print cell ... RawCell(row=1, column='A', coordinate='A1', internal_value=1.0, data_type='n', style_id='0', number_format='general') RawCell(row=1, column='B', coordinate='B1', internal_value=10.0, data_type='n', style_id='0', number_format='general') ... 
+7
source

Source: https://habr.com/ru/post/985662/


All Articles