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

Escape formulae on export #540

Merged
merged 7 commits into from
Mar 3, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
22 changes: 13 additions & 9 deletions src/tablib/formats/_xlsx.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,16 @@ def detect(cls, stream):
return False

@classmethod
def export_set(cls, dataset, freeze_panes=True, invalid_char_subst="-"):
def export_set(cls, dataset, freeze_panes=True, invalid_char_subst="-", escape=False):
"""Returns XLSX representation of Dataset.

If dataset.title contains characters which are considered invalid for an XLSX file
sheet name (http://www.excelcodex.com/2012/06/worksheets-naming-conventions/), they will
be replaced with `invalid_char_subst`.

If escape is True, formulae will have the leading '=' character removed.
This is a security measure to prevent formulae from executing by default
in exported XLSX files.
"""
wb = Workbook()
ws = wb.worksheets[0]
Expand All @@ -50,19 +54,16 @@ def export_set(cls, dataset, freeze_panes=True, invalid_char_subst="-"):
if dataset.title else 'Tablib Dataset'
)

cls.dset_sheet(dataset, ws, freeze_panes=freeze_panes)
cls.dset_sheet(dataset, ws, freeze_panes=freeze_panes, escape=escape)

stream = BytesIO()
wb.save(stream)
return stream.getvalue()

@classmethod
def export_book(cls, databook, freeze_panes=True, invalid_char_subst="-"):
def export_book(cls, databook, freeze_panes=True, invalid_char_subst="-", escape=False):
"""Returns XLSX representation of DataBook.

If dataset.title contains characters which are considered invalid for an XLSX file
sheet name (http://www.excelcodex.com/2012/06/worksheets-naming-conventions/), they will
be replaced with `invalid_char_subst`.
See export_set().
"""

wb = Workbook()
Expand All @@ -75,7 +76,7 @@ def export_book(cls, databook, freeze_panes=True, invalid_char_subst="-"):
if dset.title else 'Sheet%s' % (i)
)

cls.dset_sheet(dset, ws, freeze_panes=freeze_panes)
cls.dset_sheet(dset, ws, freeze_panes=freeze_panes, escape=escape)

stream = BytesIO()
wb.save(stream)
Expand Down Expand Up @@ -125,7 +126,7 @@ def import_book(cls, dbook, in_stream, headers=True, read_only=True):
dbook.add_sheet(data)

@classmethod
def dset_sheet(cls, dataset, ws, freeze_panes=True):
def dset_sheet(cls, dataset, ws, freeze_panes=True, escape=False):
"""Completes given worksheet from given Dataset."""
_package = dataset._package(dicts=False)

Expand Down Expand Up @@ -166,3 +167,6 @@ def dset_sheet(cls, dataset, ws, freeze_panes=True):
cell.value = col
except (ValueError, TypeError):
cell.value = str(col)

if escape and cell.data_type == 'f' and cell.value.startswith('='):
cell.value = cell.value.replace("=", "")
63 changes: 63 additions & 0 deletions tests/test_tablib.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from uuid import uuid4

from MarkupPy import markup
from openpyxl.reader.excel import load_workbook

import tablib
from tablib.core import Row, detect_format
Expand Down Expand Up @@ -1117,6 +1118,68 @@ def test_xlsx_cell_values(self):
data = tablib.Dataset().load(fh)
self.assertEqual(data.headers[0], 'Hello World')

def test_xlsx_export_set_escape_formulae(self):
"""
Test that formulae are sanitised on export.
"""
data.append(('=SUM(1+1)',))
_xlsx = data.export('xlsx')

# read back using openpyxl because tablib reads formulae as values
wb = load_workbook(filename=BytesIO(_xlsx))
ws = wb.active
self.assertEqual('=SUM(1+1)', ws['A1'].value)

_xlsx = data.export('xlsx', escape=True)
hugovk marked this conversation as resolved.
Show resolved Hide resolved
wb = load_workbook(filename=BytesIO(_xlsx))
ws = wb.active
self.assertEqual('SUM(1+1)', ws['A1'].value)
hugovk marked this conversation as resolved.
Show resolved Hide resolved

def test_xlsx_export_book_escape_formulae(self):
"""
Test that formulae are sanitised on export.
"""
data.append(('=SUM(1+1)',))
_book = tablib.Databook()
_book.add_sheet(data)
_xlsx = _book.export('xlsx')

# read back using openpyxl because tablib reads formulae as values
wb = load_workbook(filename=BytesIO(_xlsx))
ws = wb.active
self.assertEqual('=SUM(1+1)', ws['A1'].value)

_xlsx = _book.export('xlsx', escape=True)
wb = load_workbook(filename=BytesIO(_xlsx))
ws = wb.active
self.assertEqual('SUM(1+1)', ws['A1'].value)

def test_xlsx_export_set_escape_formulae_in_header(self):
data.headers = ('=SUM(1+1)',)
_xlsx = data.export('xlsx')
wb = load_workbook(filename=BytesIO(_xlsx))
ws = wb.active
self.assertEqual('=SUM(1+1)', ws['A1'].value)

_xlsx = data.export('xlsx', escape=True)
wb = load_workbook(filename=BytesIO(_xlsx))
ws = wb.active
self.assertEqual('SUM(1+1)', ws['A1'].value)

def test_xlsx_export_book_escape_formulae_in_header(self):
data.headers = ('=SUM(1+1)',)
_book = tablib.Databook()
_book.add_sheet(data)
_xlsx = _book.export('xlsx')
wb = load_workbook(filename=BytesIO(_xlsx))
ws = wb.active
self.assertEqual('=SUM(1+1)', ws['A1'].value)

_xlsx = _book.export('xlsx', escape=True)
wb = load_workbook(filename=BytesIO(_xlsx))
ws = wb.active
self.assertEqual('SUM(1+1)', ws['A1'].value)

def test_xlsx_bad_dimensions(self):
"""Test loading file with bad dimension. Must be done with
read_only=False."""
Expand Down