Openpyxl 遍历单元格,无法将单元格与字符串进行比较

Openpyxl iterating through cells, can't compare cells to string

我在遍历工作簿中的每个单元格并将调用的值与字符串对象进行比较时遇到问题。我能够成功地与工作簿中的日期时间对象进行比较,但是当涉及到常规 'String' 对象时,没有任何内容被打印,单元格也没有更新。

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)

您应该能够毫无问题地将日期和字符串读写到 Excel 格式的文件中。下面的代码显示了这适用于两种类型的单元格内容。

OP 试图匹配的字符串包含一个 unicode 破折号字符 '\u2013',它与 ASCII '-' 字符不匹配,因此字符串不匹配。以下示例中的字符串使用此 unicode 短划线字符。

# -*- 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"')

运行 这个在 Python 3.6 上产生这个输出:

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"