如何在xlsxwriter中将列设置为DATE格式

时间:2016-04-05 20:14:42

标签: python excel format xlsxwriter

我正在开发一个项目,我正在写一个xlsx电子表格,需要格式化一个列为'Date'。我让程序运行,除了列格式之外的所有格式仍然设置为'常规'。

以不同的方式尝试使用不同的代码来查看是否有人回答。:

for row in cur.execute('''SELECT `Mapline`,`Plant`,`Date`,`Action` from AEReport'''):
    lengthOfHeadings = len(row)
    output = '%s-%s.xlsx' % ("AEReport",now.strftime("%m%d%Y-%H%M"))
    workbook = xlsxwriter.Workbook(output, {'strings_to_numbers':True})
    worksheet = workbook.add_worksheet()

    format=workbook.add_format({'font_size':'8','border':True})
    format2=workbook.add_format({'font_size':'8','border':True,'num_format':'mm/dd/yy hh:mm'})
    count = 0
    for name in range(0,lengthOfHeadings):
        if name==row[2]:
            name=int(name)
            worksheet.write(counter, count, row[name],format2)
    else:
        worksheet.write(counter, count, row[name],format)
    count += 1
counter += 1

Slihthinden

3 个答案:

答案 0 :(得分:2)

要使日期时间格式有效,您必须将日期值转换为excel serial date value

以下是一个示例,说明它是如何工作的:

import pandas as pd
data = pd.DataFrame({'test_date':pd.date_range('1/1/2011', periods=12, freq='M') })
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')

data.test_date = data.test_date - pd.datetime(1899, 12, 31)

pd.core.format.header_style = None    
data.to_excel(writer, sheet_name='test', index=False)

workbook  = writer.book
worksheet = writer.sheets['test']

formatdict = {'num_format':'mm/dd/yyyy'}
fmt = workbook.add_format(formatdict)

worksheet.set_column('A:A', None, fmt)

writer.save()

这是输出的样子: enter image description here

答案 1 :(得分:1)

from datetime import datetime

date_format = workbook.add_format({'num_format':'yyyy-mm-dd hh:mm:ss'})

worksheet.write(0, 0, datetime.today(),date_format)

结果: image from Excel Generated

答案 2 :(得分:-1)

date = workbook.add_format({'num_format':'dd-mm-yyyy'})

worksheet.write(1,1,02-12-199,date)