如何使用openpyxl打印或修改单元格值?
这是我的代码。 path2是创build和修改的新文件的path。 .xlsx文件中的单元格确实包含“2017/4/2017”
wb = openpyxl.load_workbook(path2, read_only=False) ws = wb.active for row in ws.iter_rows(): for cell in row: if cell.internal_value == "4/1/2017": print(cell.value) cell.internal_value = endDate wb.save(path2)
您将单元格值与string"4/1/2017"
,但单元格实际上可能包含Excel中格式化的date值,看起来像4/1/2017' in the spreadsheet. If the cell actually contains a date, then
4/1/2017' in the spreadsheet. If the cell actually contains a date, then
openpyxl will read it as a
date时间对象will read it as a
,您需要使用正确的值针对date时间testing单元格值。
import datetime if cell.value == datetime.datetime(2017, 4, 1): print(cell.value)
date的cell.internal_value
是一个float
值,这是Excel存储date的方式。 如果你想testing这个,你需要把它与date的浮点数表示法进行比较。
如果您有指定date的string,并且可以使用datetime.datetime.strptime()
将string转换为date时间对象,以便与单元格内容进行比较。
date = datetime.datetime.strptime("4/1/2017", "%m/%d/%Y") if cell.value == date: print(cell.value)