在一列中更改日期格式(替换,插入列,附加),有什么方法可以更新吗? ..一定要简单

时间:2019-06-15 16:12:00

标签: python excel openpyxl

需要在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中的现有值。我被困住了。

谢谢。

2 个答案:

答案 0 :(得分:0)

如果您只是想让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")

答案 1 :(得分:0)

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

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