【问题标题】:Change dates format in one column (replace, insert column, append), any way to update? ..it must be simple在一列中更改日期格式(替换、插入列、追加),有什么方法可以更新吗? ..它必须很简单
【发布时间】:2019-06-15 16:12:00
【问题描述】:

需要更改 Excel 列中的日期格式。

我可以进入单个单元格,但如果用“proper_date”更新整个列,我会卡住

wb = load_workbook(...)
ws = wb['Lista']
daty_wystawienia = ws['G']

# This solution works but assigning values to first column under the chart

for daty in daty_wystawienia:
    date_string = daty.value
    if re.search('[0-9-]', str(date_string)):
        proper_date = datetime.datetime.strptime(date_string, '%d-%m-%Y').strftime('%y.%m.%d')
        for row in range(1): 
            ws.append([proper_date])  

#tried to make last line: daty_wystawienia.append([proper_date]) but got:
AttributeError: 'tuple' object has no attribute 'append'

wb.save(...)



# Also tried this, and only this seems to work. Meaning replacing values with other correctly formatted, but I need this applied to whole column at once:


wb = load_workbook(...)
ws = wb['Lista polis']
daty_wystawienia = ws['G']


ws['G6'] = "19.05.06"
ws['G7'] = "19.05.06"
ws['G8'] = "19.05.06"

ws['G10'] = "19.05.07"
ws['G11'] = "19.05.07"

# or replace

for i in ws['G']:
        ws['G9'] = ws['G9'].value.replace('06-05-2019', '10000000000')


wb.save(...)

有什么方法可以使用 openpyxl 替换、附加、覆盖 excel 中的现有值。我被困在这个问题上。

提前致谢。

【问题讨论】:

    标签: python excel openpyxl


    【解决方案1】:

    如果您只是希望 Excel 更改单元格的格式以便根据需要显示日期,这就是我为列所做的:

    from openpyxl import load_workbook
    
    book = load_workbook('Example.xlsx')
    ws = book['Sheet1']
    
    for x in range (1, 500):
        _cell = ws.cell(x,1)
        _cell.number_format = '[$-en-GB]dd-mmm-yyyy' 
    
    book.save("Dates.xlsx")
    

    【讨论】:

      【解决方案2】:

      感谢您的努力。它看起来很漂亮,但由于某种原因它对我不起作用。 我是这样经历的:

      def date_of_issuance():
          for i in ws.iter_rows():
              for cell in i:
                  d_w = 'Date of issuance'
                  if cell.value == d_w:
                      c = cell.column
                      col = column_index_from_string(c)
                      r = cell.row
                      for daty in ws[c]:
                          date_string = daty.value
                          if re.search('[0-9]', str(date_string)):
                              proper_date = datetime.datetime.strptime(date_string, '%d-%m-%Y').strftime('%y-%m-%d')
                              date = datetime.datetime.strptime(proper_date, '%y-%m-%d').date()
                              for j in range(1):
                                  ws.cell(row=r+1, column=col, value=date)
                                  r += 1
      

      【讨论】:

        猜你喜欢
        • 2015-02-03
        • 1970-01-01
        • 2013-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-29
        • 1970-01-01
        相关资源
        最近更新 更多