【问题标题】:Formatting date with openpyxl使用 openpyxl 格式化日期
【发布时间】:2015-06-20 17:14:25
【问题描述】:

您好,我正在尝试创建一个 python 程序,该程序使用 openpyxl 来验证 excel 表中的两个单元格 (1)start_date 和 (2)end_date,以检查 current_date 是否介于两者之间。有人对我如何做到这一点有任何指示吗?

我无法将日期转换为我可以操作的变量。当我把这行:

B2 包含一个日期

日期 = 打印(sheet_ranges["B2"].value)

然后日期等于“无”

所以任何帮助都会非常感谢您。

  ###Adam Giancola
###June 16th 2015
###This program will open and excel file and play with some data in the cells
###This documentation is helpful:
#   http://openpyxl.readthedocs.org/en/latest/usage.html#read-an-existing-workbook



#VERSION 1: This program can read an inputted number and track the nuber of times it is used

#VERSION 2: This program will check if the coupon is expired

import sys
import openpyxl
from openpyxl import Workbook
from datetime import datetime
from openpyxl import load_workbook
import re

try:
    while(1):
        
        

        
        match_flag = 0
        #Assign varialble to both Workbook & Sheet
        wb = openpyxl.load_workbook(filename = 'coupon_book.xlsx')
        sheet_ranges = wb.get_sheet_by_name('Sheet1')

        date = print(sheet_ranges["B2"].value)
        print(date)
        
        #Print data from an array
        #print(sheet_ranges['A1'].value)


        input_value = eval(input("Hello please enter a coupon code: "))
        #Reads inputs as a number rather than a character



        for row in sheet_ranges.iter_rows():
           #data = row[0].value   #no need for this line
            
                if row[0].value == input_value:
                        
                        match_flag = 1
                        temp = row[3].value
                        row[3].value = temp - 1
                        if match_flag == 1:
                            print("We have a match!")
                 
                           

                
        if match_flag == 0:
            print("Sorry your coupon is not valid")
                    

        wb.save('coupon_book.xlsx')




    

【问题讨论】:

  • 没有更多信息无法回答这个问题。 sheet_ranges 是什么?您对哪些细胞感兴趣?
  • sheet_ranges 只是 Excel 工作表的名称。
  • 请包含更多代码(检查格式指南)以及您感兴趣的单元格。
  • 好的,我们就说'B2'
  • 根据其他答案date = print(…) 将始终为无。如果 ws['B2'] 具有正确的数字格式,它将被转换为 Python 日期时间。您可以拨打cell.is_date查询。

标签: python date openpyxl


【解决方案1】:

我想说你只需要摆脱你的print

date = sheet_ranges["B2"].value

print 返回None,这就是为什么您要获取该值,而不是单元格中的值。

【讨论】:

  • 我明白了,但我需要评估单元格内的值。我正在尝试找到一种从单元格中提取日、月和年的方法。我发现这篇文章几乎与我正在尝试做的事情相反。
  • @A.Cola - 如果这个答案是“我正在尝试做的事情的逆转”,那么你为什么接受它?
  • 对不起,我认为这是一个赞成票!你的回答很好,我的问题是如何将我的 None 类型转换为整数或字符串,或者我可以在我的程序中操作的东西。但我确实找到了另一篇与我想做的相反的帖子(写而不是读)stackoverflow.com/questions/24370385/…
  • 如何把你的 None 变成别的东西?摆脱打印(它仍然存在)......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-31
  • 1970-01-01
  • 2021-03-15
  • 2013-04-06
  • 2012-05-05
  • 2015-09-29
  • 2018-05-26
相关资源
最近更新 更多