Search code examples
pythonexport-to-excelopenpyxl

Assign cells to a variable with Openpyxl


from openpyxl import load_workbook,workbook   
book = load_workbook('myfile.xlsx')
sheet = book.get_active_sheet()
for r in sheet.rows:
    for cell in r:
       firstname = cell.value(row=r, column='1')
       lastname = cell.value(row=r, column='2')
       print firstname, lastname

I want to assign each cell value on the current row to a seperate variable. When I try the above code I get the error:

TypeError: 'unicode' object is not callable

Any help greatly appreciated, thanks.


Solution

  • Ok so I've figured out where I failed here, as embarassed as I am to admit it!

    When I checked what values I was actually trying to feed Openpyxl the error was clear, the "r" variable was a string full of data rather than an integer. Using a simple "rowcount" like..

    rowcount = 0
    for r in ws.rows:
        firstname = ws.cell(row = rowcount, column = 0)
        lastname = ws.cell(row = rowcount, column = 1)
        rowcount = rowcount + 1
        print firstname.value, lastname.value
    

    Seems to have done the trick.