如何使用openpyxl获取单元格的实际值

How to get the actual value of a cell with openpyxl

我正在尝试从 excel sheet 中获取值,但是有一列填满了日期。

Image of that column

我想准确获取单元格中的值(21 年 11 月 22 日),但我得到的值是 2021-11-22 00:00:00

要访问特定单元格的值,您将使用:

value = worksheet.cell(row, column)

Openpyxl 不会自行评估单元格内容或格式,因为它实际上 运行 Excel,只是访问文件。因此,当您获取单元格值时,您获取的是它包含的日期时间对象,而不是您在打开 Excel 时看到的显示格式。您可以按照@Gedas 的建议进行操作,并使用 cell.number_format 获取单元格格式,然后尝试基于此设置格式。但是按照@Charlie 的建议并自己格式化会更容易 (see the documentation for datetime for more information on formatting and format codes)。

import openpyxl as op
import datetime as dt

wb = op.load_workbook("Date_format.xlsx")
ws = wb["Sheet1"]

your_date = ws.cell(row=1, column=1).value
your_formatted_date = your_date.strftime("%d-%b-%y")
print(your_formatted_date)

>>>
22-Nov-21