仅将日期格式应用于xlwt的日期列

时间:2012-06-25 07:27:40

标签: python-2.7 export-to-excel xlwt

我有数据库搜索的结果,其中某些列有日期,但没有其他列。我需要帮助才能写出

data = [['556644', 'Mr', 'So', 'And', 'So', Decimal('0.0000'), datetime.datetime(2012, 2, 25, 0, 0), '', False, datetime.datetime(2013, 6, 30, 0, 0)],...]

进入Excel电子表格以便

easyxf(num_format_str='DD/MM/YYYY')

仅适用于日期时间列。我对Python很陌生,现在已经有好几天了。谢谢!

3 个答案:

答案 0 :(得分:1)

这是使用pyodbc从SQL服务器导入的,因此来自cursor.fetchall()的地方:

data = [list(n) for n in cursor.fetchall()]
for row_index, row_contents in enumerate(data):
    for column_index, cell_value in enumerate(row_contents):
        xf=None
        if isinstance(data[row_index][column_index], datetime.date):
            xf = easyxf(num_format_str='DD/MM/YYYY') # sets date format in Excel
        if xf:
            sheet1.write(row_index+1, column_index, cell_value, xf)
        else:
            sheet1.write(row_index+1, column_index, cell_value)

完成! :)

答案 1 :(得分:1)

简化自我回答后:

date_xf = easyxf(num_format_str='DD/MM/YYYY') # sets date format in Excel
data = [list(n) for n in cursor.fetchall()]
for row_index, row_contents in enumerate(data):
    for column_index, cell_value in enumerate(row_contents):
        if isinstance(cell_value, datetime.date):
            sheet1.write(row_index+1, column_index, cell_value, date_xf)
        else:
            sheet1.write(row_index+1, column_index, cell_value)

答案 2 :(得分:0)

想要在Excel中为单元格写日期:

为写调用添加额外属性 - 单元格的样式:

import datetime
import xlwt

workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('test')
date_style = xlwt.easyxf(num_format_str='YYYY/MM/DD')
worksheet.write(0, 0, 'Today')
worksheet.write(1, 0, datetime.date.today(), date_style)
workbook.save('C:\\data.xls')
相关问题