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

我怕爱的太早我们不能终老 提交于 2020-01-05 05:37:14

问题


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)

回答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"


来源:https://stackoverflow.com/questions/43711327/openpyxl-iterating-through-cells-cant-compare-cells-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!