Skip to content

Commit

Permalink
Fixes #314 - Delegate type coercion to openpyxl
Browse files Browse the repository at this point in the history
Thanks Cristiano Lopes for the initial patch.
  • Loading branch information
claudep committed Oct 3, 2019
1 parent a0df54c commit d8b282a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
19 changes: 10 additions & 9 deletions tablib/formats/_xlsx.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from io import BytesIO

import openpyxl
from openpyxl.utils.exceptions import IllegalCharacterError
import tablib

Workbook = openpyxl.workbook.Workbook
Expand Down Expand Up @@ -117,25 +118,25 @@ def dset_sheet(dataset, ws, freeze_panes=True):

# bold headers
if (row_number == 1) and dataset.headers:
# cell.value = unicode('%s' % col, errors='ignore')
cell.value = unicode(col)
cell.font = bold
if freeze_panes:
# Export Freeze only after first Line
ws.freeze_panes = 'A2'

# bold separators
elif len(row) < dataset.width:
cell.value = unicode('%s' % col, errors='ignore')
cell.font = bold

# wrap the rest
else:
try:
if '\n' in col:
cell.value = unicode('%s' % col, errors='ignore')
cell.alignment = wrap_text
else:
cell.value = unicode('%s' % col, errors='ignore')
str_col_value = unicode(col)
except TypeError:
cell.value = unicode(col)
str_col_value = ''
if '\n' in str_col_value:
cell.alignment = wrap_text

try:
cell.value = col
except (ValueError, TypeError, IllegalCharacterError):
cell.value = unicode(col)
16 changes: 16 additions & 0 deletions test_tablib.py
Original file line number Diff line number Diff line change
Expand Up @@ -782,6 +782,22 @@ def test_tsv_export(self):
self.assertEqual(tsv, self.founders.tsv)


class XLSXTests(BaseTestCase):
def test_xlsx_import_set(self):
data.append(('string', 42, 21.55))
data.headers = ('string', 'integer', 'float')
_xlsx = data.xlsx
data.xlsx = _xlsx
self.assertEqual(data.dict[0]['string'], 'string')
self.assertEqual(data.dict[0]['integer'], 42)
self.assertEqual(data.dict[0]['float'], 21.55)

def test_xlsx_wrong_char(self):
"""A bad character should not crash the export"""
data.append(('string', b'\x0cf'))
data.xlsx


class JSONTests(BaseTestCase):
def test_json_format_detect(self):
"""Test JSON format detection."""
Expand Down

0 comments on commit d8b282a

Please sign in to comment.