Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: xls: add styling for date/time types #596

Merged
merged 1 commit into from
Jul 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/tablib/formats/_xls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
""" Tablib - XLS Support.
"""

import datetime
from io import BytesIO

import xlrd
Expand All @@ -12,6 +12,9 @@
# special styles
wrap = xlwt.easyxf("alignment: wrap on")
bold = xlwt.easyxf("font: bold on")
datetime_style = xlwt.easyxf(num_format_str='M/D/YY h:mm')
date_style = xlwt.easyxf(num_format_str='M/D/YY')
time_style = xlwt.easyxf(num_format_str='h:mm:ss')


class XLSFormat:
Expand Down Expand Up @@ -138,6 +141,13 @@ def dset_sheet(cls, dataset, ws):
elif len(row) < dataset.width:
ws.write(i, j, col, bold)

# format date types
elif isinstance(col, datetime.datetime):
ws.write(i, j, col, datetime_style)
elif isinstance(col, datetime.date):
ws.write(i, j, col, date_style)
elif isinstance(col, datetime.time):
ws.write(i, j, col, time_style)
# wrap the rest
else:
try:
Expand Down
18 changes: 18 additions & 0 deletions tests/test_tablib.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from pathlib import Path
from uuid import uuid4

import xlrd
from openpyxl.reader.excel import load_workbook

import tablib
Expand Down Expand Up @@ -1254,6 +1255,23 @@ def test_book_import_from_stream(self):
book = tablib.Databook().load(in_stream, 'xls')
self.assertEqual(book.sheets()[0].title, 'Founders')

def test_xls_export_with_dates(self):
date = dt.date(2019, 10, 4)
time = dt.time(14, 30)
date_time = dt.datetime(2019, 10, 4, 12, 30, 8)
data.append((date, time, date_time))
data.headers = ('date', 'time', 'date/time')
_xls = data.xls
xls_book = xlrd.open_workbook(file_contents=_xls, formatting_info=True)
row = xls_book.sheet_by_index(0).row(1)

def get_format_str(cell):
return xls_book.format_map[xls_book.xf_list[cell.xf_index].format_key].format_str

self.assertEqual('m/d/yy', get_format_str(row[0]))
self.assertEqual('h:mm:ss', get_format_str(row[1]))
self.assertEqual('m/d/yy h:mm', get_format_str(row[2]))


class XLSXTests(BaseTestCase):
def test_xlsx_format_detect(self):
Expand Down
Loading