2

我有来自数据库搜索的结果,其中一些列有日期,但其他列没有。我需要帮助写作

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 还是很陌生,而且我已经为此苦苦思索了好几天了。谢谢!

4

3 回答 3

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)

完毕!:)

于 2012-06-25T23:36:01.553 回答
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)
于 2012-07-06T17:08:28.980 回答
0

想要将日期写入 Excel 中的单元格:

向 write 调用添加一个额外的属性 - 单元格的样式:

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')
于 2013-09-12T11:23:58.163 回答