mirror of
https://github.com/kennethreitz/tablib.git
synced 2026-06-05 06:56:13 +00:00
Refs #373 - Import dates from xls files as Python datetime objects
This commit is contained in:
@@ -11,6 +11,7 @@
|
||||
### Bugfixes
|
||||
|
||||
- Fixed minimal openpyxl dependency version to 2.6.0 (#457).
|
||||
- Dates from xls files are now read as Python datetime objects (#373).
|
||||
|
||||
## 1.1.0 (2020-02-13)
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ from io import BytesIO
|
||||
import tablib
|
||||
import xlrd
|
||||
import xlwt
|
||||
from xlrd.xldate import xldate_as_datetime
|
||||
|
||||
# special styles
|
||||
wrap = xlwt.easyxf("alignment: wrap on")
|
||||
@@ -74,12 +75,19 @@ class XLSFormat:
|
||||
|
||||
dset.title = sheet.name
|
||||
|
||||
def cell_value(value, type_):
|
||||
if type_ == xlrd.XL_CELL_ERROR:
|
||||
return xlrd.error_text_from_code[value]
|
||||
elif type_ == xlrd.XL_CELL_DATE:
|
||||
return xldate_as_datetime(value, xls_book.datemode)
|
||||
return value
|
||||
|
||||
for i in range(sheet.nrows):
|
||||
if i == 0 and headers:
|
||||
dset.headers = sheet.row_values(0)
|
||||
else:
|
||||
dset.append([
|
||||
val if typ != xlrd.XL_CELL_ERROR else xlrd.error_text_from_code[val]
|
||||
cell_value(val, typ)
|
||||
for val, typ in zip(sheet.row_values(i), sheet.row_types(i))
|
||||
])
|
||||
|
||||
|
||||
Binary file not shown.
@@ -975,6 +975,12 @@ class XLSTests(BaseTestCase):
|
||||
in_stream = self.founders.xls
|
||||
self.assertEqual(detect_format(in_stream), 'xls')
|
||||
|
||||
def test_xls_date_import(self):
|
||||
xls_source = Path(__file__).parent / 'files' / 'dates.xls'
|
||||
with open(str(xls_source), mode='rb') as fh:
|
||||
dset = tablib.Dataset().load(fh, 'xls')
|
||||
self.assertEqual(dset.dict[0]['birth_date'], datetime.datetime(2015, 4, 12, 0, 0))
|
||||
|
||||
def test_xls_import_with_errors(self):
|
||||
"""Errors from imported files are kept as errors."""
|
||||
xls_source = Path(__file__).parent / 'files' / 'errors.xls'
|
||||
|
||||
Reference in New Issue
Block a user