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

时间:2017-04-30 21:06:34

标签: python excel datetime openpyxl

我在迭代工作簿中的每个单元格并将调用的值与字符串对象进行比较时遇到问题。我能够成功地与工作簿中的datetime对象进行比较,但是当涉及到常规的“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)

1 个答案:

答案 0 :(得分:0)

您应该能够毫无问题地读取和写入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"