Writing xlwt dates with Excel 'date' format

后端 未结 2 1472
别那么骄傲
别那么骄傲 2021-01-11 10:03

I\'m using xlwt to make a .xls spreadsheet, and I need to create date cells.

I\'ve got writing out numbers, and setting the number format string to make them look li

相关标签:
2条回答
  • 2021-01-11 10:46

    The number will show up in the Excel "Date" category if you use a format string that corresponds to one of Excel's built-in format strings such as dd/mm/yyy. for example:

    import xlwt
    import datetime
    
    workbook = xlwt.Workbook()
    worksheet = workbook.add_sheet('Sheet1')
    
    date_format = xlwt.XFStyle()
    date_format.num_format_str = 'dd/mm/yyyy'
    
    worksheet.write(0, 0, datetime.datetime.now(), date_format)
    
    workbook.save('date_format.xls')
    

    If you modify this example to use a format string of d/mm/yyy then the number will show up in the "Custom" category.

    Note: the above code works for the version of Excel that I tried but it is possible that this is subject to regional variation. The best thing to do is format a number in Excel with the "Date" format that you want and then, in the same dialog, click on "Custom" to see what format string is associated with the "Date" format. Then use that in your program.

    Also: There isn't any native date type in the Excel XLS format. All dates are stored as numbers plus a format. There is nothing to distinguish them from any other number with a format except for the format string. This is one of the things that makes parsing an Excel file a pain since you have to apply heuristics to determine if a cell contains a date.

    0 讨论(0)
  • 2021-01-11 10:51

    From http://www.youlikeprogramming.com/2011/04/examples-generating-excel-documents-using-pythons-xlwt/

    Entering a Date into a Cell

    
    import xlwt
    import datetime
    workbook = xlwt.Workbook()
    worksheet = workbook.add_sheet('My Sheet')
    style = xlwt.XFStyle()
    style.num_format_str = 'D-MMM-YY' # Other options: D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0
    worksheet.write(0, 0, datetime.datetime.now(), style)
    workbook.save('Excel_Workbook.xls')
    
    
    0 讨论(0)
提交回复
热议问题