Skip to content

Commit

Permalink
Factorize import book and dataset in new function import sheet
Browse files Browse the repository at this point in the history
  • Loading branch information
ClemenceAlain committed Apr 11, 2023
1 parent 438e341 commit 1e37bce
Showing 1 changed file with 16 additions and 21 deletions.
37 changes: 16 additions & 21 deletions src/tablib/formats/_xlsx.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,8 @@ def export_book(cls, databook, freeze_panes=True, invalid_char_subst="-", escape
return stream.getvalue()

@classmethod
def import_set(cls, dset, in_stream, headers=True, read_only=True, skip_lines=0):
"""Returns databook from XLS stream."""

dset.wipe()

xls_book = load_workbook(in_stream, read_only=read_only, data_only=True)
sheet = xls_book.active
def import_sheet(cls, dset, sheet, headers=True, skip_lines=0):
"""Populates dataset with sheet."""

dset.title = sheet.title

Expand All @@ -102,10 +97,20 @@ def import_set(cls, dset, in_stream, headers=True, read_only=True, skip_lines=0)
if i == skip_lines and headers:
dset.headers = row_vals
else:
if i > 0 and len(row_vals) < dset.width:
if i > skip_lines and len(row_vals) < dset.width:
row_vals += [''] * (dset.width - len(row_vals))
dset.append(row_vals)

@classmethod
def import_set(cls, dset, in_stream, headers=True, read_only=True, skip_lines=0):
"""Returns databook from XLS stream."""

dset.wipe()

xls_book = load_workbook(in_stream, read_only=read_only, data_only=True)
sheet = xls_book.active
cls.import_sheet(dset, sheet, headers, skip_lines)

@classmethod
def import_book(cls, dbook, in_stream, headers=True, read_only=True):
"""Returns databook from XLS stream."""
Expand All @@ -115,19 +120,9 @@ def import_book(cls, dbook, in_stream, headers=True, read_only=True):
xls_book = load_workbook(in_stream, read_only=read_only, data_only=True)

for sheet in xls_book.worksheets:
data = tablib.Dataset()
data.title = sheet.title

for i, row in enumerate(sheet.rows):
row_vals = [c.value for c in row]
if (i == 0) and (headers):
data.headers = row_vals
else:
if i > 0 and len(row_vals) < data.width:
row_vals += [''] * (data.width - len(row_vals))
data.append(row_vals)

dbook.add_sheet(data)
dset = tablib.Dataset()
cls.import_sheet(dset, sheet, headers)
dbook.add_sheet(dset)

@classmethod
def dset_sheet(cls, dataset, ws, freeze_panes=True, escape=False):
Expand Down

0 comments on commit 1e37bce

Please sign in to comment.