【问题标题】:Changing date-format to text in xlsx using openpyxl使用 openpyxl 将日期格式更改为 xlsx 中的文本
【发布时间】:2018-04-09 09:14:27
【问题描述】:

我编写了一个从 excel 工作簿中读取并编写新工作簿的脚本。 每行是一个单独的对象,其中一列是日期。 我已使用 datetime 将日期写为 NamedStyle 以获得我认为正确的格式:

    date_style = NamedStyle(name='datetime', number_format='YYYY-MM-DD')
    for row in range(2,ws_kont.max_row+1):
        ws_kont.cell(row = row, column = 4).style = date_style

问题是我需要将此 excel 工作簿导入一个古老的数据库,该数据库由于某种原因不接受日期格式,只接受像“yyyy-dd-mm”这样的文本。 我无法将这些单元格重写为文本。

我尝试过使用 =TEXT 公式,但这不起作用,因为您不能使用单元格本身来计算结果,除非我复制该列以在公式中引用:

name = str(ws_teg.cell(row = row, column = 4).coordinate)
date_f = "yyyy-mm-dd"
ws_kont[name] = "=TEXT(%s,%s)" % (name, date_f)

我需要在几个脚本中做很多地方,所以我想知道是否有更简单的方法来做到这一点?

PS。我只是一个考古学家,试图在工作日通过一些简单的代码来自动化一些任务,如果我看起来有点慢,请放轻松。

【问题讨论】:

    标签: python excel openpyxl


    【解决方案1】:

    找到另一篇使用最少代码的文章:

    writer = pd.ExcelWriter('Sample_Master_Data_edited.xlsx', engine='xlsxwriter', 
                            date_format='mm/dd/yyyy', datetime_format='mm/dd/yyyy')
    

    Reference

    【讨论】:

      【解决方案2】:

      很可能,仅更改日期的格式 是不够的 - 您必须将日期存储为字符串而不是日期时间对象。

      遍历列并使用datetime.strftime格式化日期:

      for row in range(1, ws_kont.max_row+1):
          cell = ws_kont.cell(row = row, column = 4)
          cell.value = cell.value.strftime('%Y-%m-%d')
      

      【讨论】:

      • 当某件事感觉应该很简单时,通常是这样。非常感谢!
      猜你喜欢
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-23
      • 1970-01-01
      相关资源
      最近更新 更多