How to format cell with datetime object of the form 'yyyy-mm-dd hh:mm:ss' in Excel using openpyxl

后端 未结 6 1190
我在风中等你
我在风中等你 2021-01-02 06:57

So, given:

dttm = datetime.datetime.strptime(\"2014-06-23 13:56:30\", \"%Y-%m-%d %H:%M:%S\")
ws[\'A1\'] = dttm

The result in excel is that

6条回答
  •  无人及你
    2021-01-02 07:08

    from openpyxl import load_workbook
    from openpyxl.styles import NamedStyle
    
    xlsx_file = args.xlsx_file.name
    
    # openning:
    wb = load_workbook(filename = xlsx_file)
    
    
    # create date style:
    date_style = NamedStyle(name='date_style', number_format='DD.MM.YYYY HH:MM:MM')
    
    # apply the style to the column H of the default sheet:
    ws = wb.active
    for row in ws[2:ws.max_row]:  # skip the header
        cell = row[7]             # column H
        cell.style = date_style
    
    # saving:
    wb.save(xlsx_file)
    

    Edit: the above works for me, but somehow does not work on my coleagues machine. Converting the cell to string fixed that:

    import datetime
    
    from openpyxl import load_workbook
    from openpyxl.styles import Alignment
    
    xlsx_file = 'file.xlsx'
    
    date_format = '%Y-%b-%d'
    
    # openning:
    wb = load_workbook(filename = xlsx_file)
    
    # we also center align that column:
    alignment = Alignment(horizontal='center')
    
    # apply python date format to column H of the default sheet, and convert the column to Excel text:
    ws = wb.active
    for row in ws[2:ws.max_row]:        # skip the header
        cell = row[7]   # column H
        if isinstance(cell.value, datetime.datetime):
            cell.value = cell.value.strftime(date_format)
            cell.alignment = alignment
    
    # saving:
    wb.save(xlsx_file)
    

    The same wrapped in a script:

    #!/usr/bin/env python3
    
    import argparse
    import datetime
    
    from openpyxl import load_workbook
    from openpyxl.styles import Alignment
    
    
    # ==============
    ## parsing args:
    
    desc="""
    
    Applies python date format to a given column of the xlsx file (default sheet) and converts the column to a Excel text format.
    
    Dependencies:
    pip3 install --user --upgrade openpyxl
    """
    
    parser = argparse.ArgumentParser(description=desc, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('--version', action='version', version='%(prog)s 0.01')
    
    parser.add_argument('-f', '--file',
                        help = "xlsx file",
                        dest = 'xlsx_file',
                        type = argparse.FileType('r'),
                        )
    
    parser.add_argument('-c', '--column',
                        help = "column (starting from A) (default to %(default)s)",
                        dest = 'column',
                        type = str,
                        default = "A",
                        )
    
    parser.add_argument('-d', '--date-format',
                        help = "date format to use, e.g. %%d.%%m.%%Y (default to %(default)s)",
                        dest = 'date_format',
                        type = str,
                        default = '%Y-%b-%d',
                        )
    
    args = parser.parse_args()
    
    
    # =========
    ## program:
    
    xlsx_file = args.xlsx_file.name
    
    column_number = sum(
        [ ord(char) - 97 + i*26  for i,char in enumerate(
            list( args.column.lower() )
            ) ]
    )
    
    # openning:
    wb = load_workbook(filename = xlsx_file)
    
    # we also center align that column:
    alignment = Alignment(horizontal='center')
    
    # apply python date format to a given column of the default sheet, and convert the column to Excel text:
    ws = wb.active
    for row in ws[2:ws.max_row]:        # skip the header
        cell = row[column_number]
        if isinstance(cell.value, datetime.datetime):
            cell.value = cell.value.strftime(args.date_format)
            cell.alignment = alignment
    
    # saving:
    wb.save(xlsx_file)
    

提交回复
热议问题