Skip to content Skip to sidebar Skip to footer

Openpyxl Iterating Through Cells, Can't Compare Cells To String

I am having issues iterating through every cell in a workbook and comparing the call's value to a string object. I am able to successfully compare to datetime objects in the workb

Solution 1:

You should be able to read and write dates and strings to an Excel formatted file without problems. The code below shows this working for both types of cell contents.

The string that the OP was trying to match contained a unicode dash character '\u2013', which doesn't match with the ASCII '-' character, so the strings weren't matching. The strings in the example below use this unicode dash character.

# -*- coding: utf-8 -*-
import openpyxl
import datetime

#create a workbook containing a string and save it
wb = openpyxl.Workbook()
ws = wb.active
ws['A1'] = datetime.datetime(2017, 4, 1)
ws['A2'] = '4/1/2017–4/30/2017' # The dash between the dates is '\u2013'
wb.save('Test.xlsx')

#open that workbook and read it
wb = openpyxl.load_workbook('Test.xlsx', read_only=False)
ws = wb.active

for row in ws.iter_rows():
    for cell in row:
        print('Cell: [{}] is type({}): "{}"'.format(cell.coordinate, type(cell.value).__name__, cell.value))
        if cell.value == '4/1/2017–4/30/2017':
            print('Found "4/1/2017–4/30/2017"')

Running this on Python 3.6 produces this output:

Cell: [A1] is type(datetime): "2017-04-01 00:00:00"
Cell: [A2] is type(str): "4/1/2017–4/30/2017"
Found "4/1/2017–4/30/2017"

Post a Comment for "Openpyxl Iterating Through Cells, Can't Compare Cells To String"