From 77469ef6556f356e93ed37e5e10b8ccccc2fbb46 Mon Sep 17 00:00:00 2001 From: Cristiano Lopes Date: Mon, 11 Sep 2017 12:47:51 +0100 Subject: [PATCH 1/2] Delegate type coercion to openpyxl --- tablib/formats/_xlsx.py | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/tablib/formats/_xlsx.py b/tablib/formats/_xlsx.py index 411e0fc..0fb42db 100644 --- a/tablib/formats/_xlsx.py +++ b/tablib/formats/_xlsx.py @@ -120,33 +120,29 @@ def dset_sheet(dataset, ws, freeze_panes=True): if (row_number == 1) and dataset.headers: # ws.cell('%s%s'%(col_idx, row_number)).value = unicode( # '%s' % col, errors='ignore') - ws.cell('%s%s'%(col_idx, row_number)).value = unicode(col) style = ws.get_style('%s%s' % (col_idx, row_number)) style.font.bold = True if freeze_panes: # As already done in #53, but after Merge lost: # Export Freeze only after first Line ws.freeze_panes = 'A2' - + # bold separators elif len(row) < dataset.width: - ws.cell('%s%s'%(col_idx, row_number)).value = unicode( - '%s' % col, errors='ignore') style = ws.get_style('%s%s' % (col_idx, row_number)) style.font.bold = True # wrap the rest else: try: - if '\n' in col: - ws.cell('%s%s'%(col_idx, row_number)).value = unicode( - '%s' % col, errors='ignore') + str_col_value = unicode(col) + except TypeError: + str_col_value = '' + + if '\n' in str_col_value: style = ws.get_style('%s%s' % (col_idx, row_number)) style.alignment.wrap_text - else: - ws.cell('%s%s'%(col_idx, row_number)).value = unicode( - '%s' % col, errors='ignore') - except TypeError: - ws.cell('%s%s'%(col_idx, row_number)).value = unicode(col) + + ws.cell('%s%s' % (col_idx, row_number)).value = col From 79d66cd250ec4e219fb48c1a2ddc42911efeae4b Mon Sep 17 00:00:00 2001 From: Cristiano Lopes Date: Mon, 11 Sep 2017 13:05:31 +0100 Subject: [PATCH 2/2] Handle raised exceptions while setting the value on the cell Convert the value to unicode, if not enough i think the bubbling of the exception is the best thing to do --- tablib/formats/_xlsx.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tablib/formats/_xlsx.py b/tablib/formats/_xlsx.py index 0fb42db..c0fec0e 100644 --- a/tablib/formats/_xlsx.py +++ b/tablib/formats/_xlsx.py @@ -17,6 +17,7 @@ import tablib Workbook = openpyxl.workbook.Workbook ExcelWriter = openpyxl.writer.excel.ExcelWriter get_column_letter = openpyxl.cell.get_column_letter +DataTypeException = openpyxl.shared.exc.DataTypeException from tablib.compat import unicode @@ -143,6 +144,7 @@ def dset_sheet(dataset, ws, freeze_panes=True): style = ws.get_style('%s%s' % (col_idx, row_number)) style.alignment.wrap_text - ws.cell('%s%s' % (col_idx, row_number)).value = col - - + try: + ws.cell('%s%s' % (col_idx, row_number)).value = col + except (ValueError, TypeError, DataTypeException): + ws.cell('%s%s' % (col_idx, row_number)).value = unicode(col)