Openpyxl遍历单元格,无法将单元格与字符串进行比较 [英] Openpyxl iterating through cells, can't compare cells to string

查看:86
本文介绍了Openpyxl遍历单元格,无法将单元格与字符串进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在遍历工作簿中的每个单元格并将调用的值与字符串对象进行比较时遇到问题.我能够成功地将其与工作簿中的日期时间对象进行比较,但是当涉及到常规的字符串"对象时,什么也不会打印,并且单元格也不会更新.

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)

推荐答案

您应该能够将日期和字符串读写到Excel格式的文件中,而不会出现问题.下面的代码显示了这两种类型的单元格内容都可以使用.

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.

OP尝试匹配的字符串包含Unicode破折号'\u2013',该字符与ASCII '-'字符不匹配,因此字符串不匹配.下面的示例中的字符串使用此Unicode破折号.

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

在Python 3.6上运行此命令会产生以下输出:

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"

这篇关于Openpyxl遍历单元格,无法将单元格与字符串进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆