【发布时间】:2014-05-01 22:23:26
【问题描述】:
我正在使用 xlrd 从 Excel 电子表格中读取一堆原始数据,进行各种计算和重新格式化,然后使用 xlsxwriter 将结果写入新工作簿。
我能够使用 xlrd 正确读取日期数据并转换为 datetime 对象,但是当我尝试使用 xlsxwriter 编写它时出现错误。我已经阅读了 xlsxwriter 上的所有 SO 帖子以及 excel 如何格式化数据等,并在 Google 上搜索过,但似乎无法弄清楚。
我的代码是:
in_wb = xlrd.open_workbook("in_book.xlsx")
in_sheet = in_wb.sheet_by_name("in_sheet")
out_wb = xlsxwriter.Workbook("out_book.xlsx")
out_sheet = out_wb.add_worksheet("out_sheet")
date_format = out_wb.add_format({'num_format': 'YYYY-MM-DD HH:DD:SS'})
as_tuple = xlrd.xldate_as_tuple(in_sheet.cell_value(0, 0), in_wb.datemode)
as_datetime = datetime.datetime(as_tuple[0], as_tuple[1], as_tuple[2] , as_tuple[3], as_tuple[4], as_tuple[5])
out_sheet.write_datetime(0, 0, as_datetime, date_format)
#print details just to be sure
print as_datetime #prints it in exactly the format I want
print type(as_datetime) #says it is of type 'datetime.datetime'
完整的 Traceback 错误是(不包括我的 py 文件中的第一次调用):
File "C:\Python27\lib\site-packages\xlsxwriter\worksheet.py", line 57, in cell_wrapper
return method(self, *args, **kwargs)
File "C:\Python27\lib\site-packages\xlsxwriter\worksheet.py", line 668, in write_datetime
number = self._convert_date_time(date)
File "C:\Python27\lib\site-packages\xlsxwriter\worksheet.py", line 3267, in _convert_date_time
return datetime_to_excel_datetime(dt_obj, self.date_1904)
File "C:\Python27\lib\site-packages\xlsxwriter\utility.py", line 576, in datetime_to_excel_datetime
raise TypeError("Unknown or unsupported datetime type")
TypeError: Unknown or unsupported datetime type
Exception LookupError: 'unknown encoding: utf-8' in <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbook object at 0x030BAB50>> ignored
当我只调用普通的“out_sheet.write”时,生成的电子表格会在单元格中显示一堆“######”,但是当我单击单元格时,它会显示日期和时间,因为我想要它,当我这样做时,不知道如何驾驭这些“####”。我不关心使用 write_datetime() 或只使用 write(),我只希望它正确显示在输出表单元格中。
非常感谢您的帮助!
【问题讨论】:
-
我的代码中的最后一个打印调用产生的结果是'datetime.datetime',它应该是由 write_datetime() 函数支持的。
标签: python datetime xlsxwriter