简体   繁体   English

使用xlrd读取日期,使用xlsxwriter在Python中编写它们

[英]Using xlrd to read dates and xlsxwriter to write them in Python

I am using xlrd to read a bunch of raw data from an excel spreadsheet, do various calculations and reformatting, and then write my results to a new workbook using xlsxwriter. 我正在使用xlrd从excel电子表格中读取一堆原始数据,进行各种计算和重新格式化,然后使用xlsxwriter将我的结果写入新工作簿。

I'm able to read in the date data correctly using xlrd and convert to a datetime object, but when I try to write this using xlsxwriter I get errors. 我能够使用xlrd正确读取日期数据并转换为datetime对象,但是当我尝试使用xlsxwriter写这个时,我会收到错误。 I've read all the SO posts on xlsxwriter and how excel formats data, etc., and googled it, but can't seem to figure it out. 我已经阅读了xlsxwriter上的所有SO帖子以及excel如何格式化数据等等,并用谷歌搜索它,但似乎无法弄明白。

My code is: 我的代码是:

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'

The full Traceback error is (excluding the very first call from my py file): 完整的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

When I call just the ordinary 'out_sheet.write' instead, the resulting spreadsheet shows a bunch of '######' in the cell, but when I click on the cell it shows the date and time as I wanted it, not sure how to get ride of these '####' when I do it this way. 当我只调用普通的'out_sheet.write'时,生成的电子表格会在单元格中显示一堆'######',但是当我点击单元格时,它会显示我想要的日期和时间,当我这样做的时候,不知道如何骑这些'####'。 I don't care about using write_datetime() or just write(), I just want it to show up correctly in the output sheet cells. 我不关心使用write_datetime()或只是write(),我只是想让它在输出表单元格中正确显示。

Thanks very much for your help! 非常感谢您的帮助!

I installed the latest versions of xlrd (0.9.3) and xlsxwriter (0.5.3) and was able to run your sample program without any error: 我安装了最新版本的xlrd (0.9.3)和xlsxwriter (0.5.3),并且能够运行您的示例程序而不会出现任何错误:

import xlrd
import xlsxwriter
import datetime

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 as_datetime
print type(as_datetime)

out_wb.close()

Note, I added a workbook.close() to the end to avoid any file closing issues and to make any error messages cleaner. 注意,我在最后添加了一个workbook.close() ,以避免任何文件关闭问题并使任何错误消息更清晰。 This ran and generated the expected xlsx file and output: 这运行并生成了预期的xlsx文件和输出:

$ python so01.py
2014-05-02 00:00:00
<type 'datetime.datetime'> 

Note, as of version 0.93 xlrd also supports a xldate_as_datetime() function. 注意,从版本0.93开始, xlrd还支持xldate_as_datetime()函数。 So you could do the conversion more simply as follows: 因此,您可以更简单地执行转换,如下所示:

as_datetime = xlrd.xldate.xldate_as_datetime(in_sheet.cell_value(0, 0), 
                                             in_wb.datemode)

out_sheet.write_datetime(0, 0, as_datetime, date_format)

And finally: 最后:

When I call just the ordinary 'out_sheet.write' instead, the resulting spreadsheet shows a bunch of '######' in the cell, but when I click on the cell it shows the date and time as I wanted it, 当我只调用普通的'out_sheet.write'时,生成的电子表格会在单元格中显示一堆'######',但是当我点击单元格时,它会显示我想要的日期和时间,

This is Excel's standard way of saying that the value is too big to display in the cell (since it has quite a long date format in the example above). 这是Excel的标准方式,表示该值太大而无法在单元格中显示(因为它在上面的示例中具有相当长的日期格式)。 If you widen the column width with worksheet.set_column() you should see the expected value. 如果使用worksheet.set_column()扩大列宽,则应该看到预期值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM