简体   繁体   中英

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 workbook but when it comes to regular 'String' objects nothing is being printed, and the cells are not updating.

wb = openpyxl.load_workbook(pathz, read_only=False)
ws = wb.active
    for row in ws.iter_rows():
        for cell in row:
            if cell.value == a:
                print("Found datetime cell")
                cell.value = newDate

            if cell.value == "Hello":
                print("Found string cell")
                cell.value = "Goodbye"

wb.save(pathz)

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 '\–' , 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM