Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Read Excel File Using Openpyxl

I want to save each Row of an excel file in a list using openpyxl.

wb = load_workbook('Shop.xlsx')
ws = wb.active

l = []

a_column = ws['A']
b_column = ws['B']

for x in range(len(a_column)):
    l.append([a_column[x].value, b_column[x].value])

print(l)

Output: [[A1, B1], [A2, B2]]

It works but does anyone know a better way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The list, for example, only works through the length of A.

>Solution :

You could use itertools.zip_longest:

a_values = [cell.value for cell in a_column]
b_values = [cell.value for cell in b_column]

list(itertools.zip_longest(a_values, b_values))
#=> [('A1', 'B1'), ('A2', 'B2'), ('A3', 'B3'), (None, 'B4'), (None, 'B5')]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading